• 周四. 4月 25th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

当用多个源文件运行python程序时,构造函数的行为与函数不同

[db:作者]

3月 7, 2023

主文件.py

from resources import *
alist[0].update()
print (blist)

资源.py

class a:
    def __init__(self):
        self.x=0
    def update(self):
        global blist
        blist=blist+[b()]
class b:
    def __init__(self):
        self.y=0
blist=[]
alist=[a()]

调用alist[0].update()时,此程序应在blist中创建类b的新实例,但在运行print(blist)后,它只显示一个空列表。我也尝试过同样的代码,其中类a的定义如下

class a:
    def __init__(self):
        self.x=0
        global blist
        blist=blist+[b()]
    def update(self):
        pass

它成功地在列表b中创建了一个实例。我真的需要它来用函数而不是构造函数创建另一个实例,我该怎么做?如有任何意见,我们将不胜感激

另外,只有在运行多个源代码文件时才会发生这种情况

Tags:

文件实例frompyself列表initdefupdateglobalclassresourcesprintalistblist1条回答网友

1楼 ·

发布于 2023-03-07 00:10:57

blist=blist+[b()]重新定义了blist。它不会修改原始对象,这就是另一个源文件中的blist所指向的对象

您应该.append到原始列表:

blist.append(b())

《当用多个源文件运行python程序时,构造函数的行为与函数不同》有37个想法
  1. of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again

  2. Fantastic site Lots of helpful information here I am sending it to some friends ans additionally sharing in delicious And of course thanks for your effort

  3. Wow, wonderful blog structure! How lengthy have you ever been running a blog
    for? you make running a blog look easy. The entire look
    of your website is great, let alone the content
    material! You can see similar here sklep online

  4. PBN sites
    We shall build a structure of private blog network sites!

    Advantages of our self-owned blog network:

    WE DO everything so Google doesn’t grasp that this A self-owned blog network!!!

    1- We purchase web domains from different registrars

    2- The primary site is hosted on a virtual private server (Virtual Private Server is high-speed hosting)

    3- Other sites are on separate hostings

    4- We designate a distinct Google ID to each site with verification in Google Search Console.

    5- We develop websites on WordPress, we do not use plugins with aided by which Trojans penetrate and through which pages on your websites are established.

    6- We refrain from reiterate templates and use only unique text and pictures

    We don’t work with website design; the client, if wished, can then edit the websites to suit his wishes

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注