我正在尝试将子类的字典与类继承合并
class Person(object):
nametag = {
"name": "Bob",
"occupation": "Nobody"
}
class Teacher(Person):
nametag = {
"occupation": "Professor",
"Subject": "Python"
}
def __init__(self):
nametag = dict(Person.nametag.items() + self.nametag.items())
最终我需要:
Teacher().nametag["name"] == "bob"
Teacher().nametag["occupation"] == "Professor"
Teacher().nametag["subject"] == "Python"
旁注,Teacher.nametag
和Person.nametag
将是非常大的词典,dict(d2.keys() + d1.keys())
是最好的方法吗?
答案 0 :(得分:3)
据推测,各个类的每个实例将会有不同的nametag
。因此,最佳实现不是您当前具有的类属性字典,而是实例属性:
class Person(object):
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
class Teacher(Person):
def __init__(self, name, occupation, subject):
super().__init__(name, occupation)
self.subject = subject
bob = Teacher("Bob", "Professor", "Python")
bob.name == "Bob"
如果您确实需要nametag
,则可以将其实现为:
class Person(object):
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
@property
def nametag(self):
return {"name": self.name,
"occupation": self.occupation}
class Teacher(Person):
def __init__(self, name, occupation, subject):
super().__init__(name, occupation)
self.subject = subject
@property
def nametag(self):
tag = super().nametag
tag["subject"] = self.subject
return tag
bob = Teacher("Bob", "Professor", "Python")
bob.nametag["name"] == "Bob"
作为旁注,
dict(d2.keys() + d1.keys())
会给你一个错误。要合并两个词典,请执行以下操作:
d1.update(d2)
答案 1 :(得分:0)
如果名称标签需要是Person和Teacher的属性,那么将它们作为彼此继承的单独类拉出来(可以使用数据库外键):
class PersonNametag(object):
name = 'Bob'
occupation = 'Nobody'
class TeacherNametag(PersonNametag):
occupation = 'Professor'
Subject = 'Python'
class Person(object):
def __init__(self):
self.nametag = PersonNametag()
class Teacher(Person):
def __init__(self):
self.nametag = TeacherNametag()