我是Python的初学者,并且我的项目类有问题。因此,结构如下:
main.py(首先,main创建世界实例)
from world import World
world = World()
World知道所有其他类的所有信息(根据需要导入所有信息),并从继承的类PersonAttributes(存储“全局”变量以便所有类都可以访问它们)中初始化带有内容的先前为空的列表。
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__()
因此,问题出在自我。专业。我已经在世界中对其进行了初始化,但是当我实例化YoungAdult((self.YOUNGADULT = YoungAdult(None,None,None,None))时,PersonAttributes中的PROFESSIONS列表为空。为什么会发生这种情况,我该如何解决?我无法摆脱self.occupation属性,因为当一个人从Teen年龄增长时,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/