初始化后获取空列表

时间:2018-03-15 15:25:23

标签: python python-3.x

我是Python的初学者,我的项目类有问题。所以结构如下:

main.py(首先,main创建世界实例)

from world import World

world = World()

World了解所有其他类的所有内容(根据需要导入所有内容),并使用内容从继承类PersonAttributes(其中"全局"变量存储以便所有类可以访问它们)初始化以前的空列表。 / p>

PersonAttributes

class PersonAttributes:

    MALE_NAMES = []
    FEMALE_NAMES = []
    SURNAMES = []
    PROFESSIONS = []

    BABY = None
    CHILD = None
    TEEN = None
    YOUNGADULT = None
    ADULT = None
    SENIOR = None
    LIFESTAGES = (BABY, CHILD, TEEN, YOUNGADULT, ADULT, SENIOR)

世界

from utilities.person_attributes import PersonAttributes
from life_stage import Baby, Child, Teen, YoungAdult, Adult, Senior

class World(PersonAttributes):

    def __init__(self):

        # Initialize names from files
        self.MALE_NAMES = self.get_male_names()
        self.FEMALE_NAMES = self.get_female_names()
        self.SURNAMES = self.get_surnames()
        self.PROFESSIONS = self.get_professions()

        # Initialize life stages
        self.BABY = Baby(None, None, None, None)
        self.CHILD = Child(None, None, None, None)
        self.TEEN = Teen(None, None, None, None)
        self.YOUNGADULT = YoungAdult(None, None, None, None)
        self.ADULT = Adult(None, None, None, None)
        self.SENIOR = Senior(None, None, None, None)

        self.population = []
        self.populate_world()

World还会导入LifeStage类,其中包含从Person继承的不同类。 YoungAdult的例子(问题出在哪里)

class YoungAdult(Person):

    def __init__()

        self.occupation = Randomizer().get_random_list_item(self.PROFESSIONS)

from utilities.person_attributes import PersonAttributes

class Person(PersonAttributes):

    def __init__():
        super(Person, self).__init__()

所以问题是自我.PROFESSIONS。我已经在世界中初始化了它,但是当我实例化YoungAdult时,(self.YOUNGADULT = YoungAdult(None,None,None,None)),PersonAttributes中的PROFESSIONS列表为空。为什么会发生这种情况,我该如何解决?我无法摆脱self.occupation属性,因为YoungAdult课程需要在青少年时期自动拥有职业。我希望你们能够理解我的意思,提前谢谢!

1 个答案:

答案 0 :(得分:1)

类和实例属性之间只有一个区别。这可能会有所启发:

>>> class K:
...     a = 1
...     def set_a(self, v):
...         self.a = v
... 
>>> k = K()
>>> K.a
1
>>> k.a
1
>>> k.set_a(3)
>>> k.a
3
>>> K.a
1
>>> K.a = 5
>>> l = K()
>>> l.a
5
>>> k.a
3

只要您设置k.a(即使是通过self.a),它就会隐藏K.a