python - 初始化后获取空列表

标签 python python-3.x

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

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

from world import World

world = World()

World 了解所有其他类的所有内容(根据需要导入所有内容),并使用内容初始化继承类 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__()

所以问题出在 self 职业上。我已经在 world 中初始化了它,但是当我实例化 YoungAdult (self.YOUNGADULT = YoungAdult(None, None, None, None)) 时,PersonAttributes 中的 PROFESSIONS 列表为空。为什么会发生这种情况以及如何解决它?我无法摆脱 self.occupation 属性,因为当一个人从青少年年龄增长时,YoungAdult 类需要自动拥有一个职业。希望大家能明白我的意思,先谢谢了!

最佳答案

类属性和实例属性之间只是存在差异。这可能会带来一些启示:

>>> 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

关于python - 初始化后获取空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49303319/

相关文章:

python - 如何排序我的数据以在 Bokeh 中制作热图?

python - 如何方便的通过dict键值过滤dict记录?

python - Flask:对单个 URL 使用 [GET, POST] 函数

python - 配置返回代码 256 - python setup.py egg_info 失败,错误代码为 1 in/tmp/pip_build_root/lxml

python - 如何将 2d libreoffice calc 命名范围分配给 python 变量。可以在 Libreoffice Basic 中完成

python - Python 中的随机性

python - 在 numpy 中计算矩阵积的轨迹的最佳方法是什么?

python - 如何使用 Tesseract API 迭代单词?

python - 使用 "bag of usual phrases"查找不寻常的短语

python - 我可以仅克隆 Git 存储库中大小低于指定限制的文件吗?