我是 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/