[英]Python - Why attributes are not inherited?
In the below code, 在下面的代码中,
>>> class Employee:
numOfEmployees = 0
raiseAmount = 1.04
def __init__(self, firstName, lastName, pay):
self.firstName = firstName
self.lastName = lastName
self.pay = pay
self.email = firstName + '.' + lastName + '@arista.com'
Employee.numOfEmployees += 1
def fullName(self):
return '{} {}'.format(self.firstName, self.lastName)
def appyRaise(self):
self.pay = int(self.pay * self.raiseAmount)
@classmethod
def setRaiseAmt(cls, amount):
cls.raiseAmount = amount
@classmethod
def createEmployee(cls, employeeStr):
firstName, lastName, pay = employeeStr.split('-')
return cls(firstName, lastName, pay)
@staticmethod
def isWorkDay(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
>>> class Developer(Employee):
pass
>>> Developer.__dict__
{'__module__': '__main__', '__doc__': None}
>>> Employee.__dict__
{'__module__': '__main__', 'createEmployee': <classmethod object at 0x7f2727731398>, 'numOfEmployees': 0, 'setRaiseAmt': <classmethod object at 0x7f27277310f8>, 'isWorkDay': <staticmethod object at 0x7f27277313d0>, 'appyRaise': <function appyRaise at 0x7f2727721f50>, 'fullName': <function fullName at 0x7f2727721ed8>, '__doc__': None, '__init__': <function __init__ at 0x7f2727721e60>, 'raiseAmount': 1.04}
>>>
Question: 题:
Why Developer.__dict__
does not show members of Employee
? 为什么
Developer.__dict__
不显示Employee
成员? What exactly are we doing with syntax class Developer(Employee)
? 语法
class Developer(Employee)
到底在做什么?
__dict__
is the attributes specifically defined on the subclass, not its parents. __dict__
是在子类上专门定义的属性,而不是其父类。 When an attribute is looked up on the subclass and not found, it will scan the MRO (method resolution order, the set of parent classes) until it finds one that does have the desired attribute. 当在子类上查找某个属性但未找到该属性时,它将扫描MRO(方法解析顺序,父类的集合),直到找到确实具有所需属性的属性。 Copying everything from the parent to the child
__dict__
would be wasteful on memory, and risk values getting out of sync (if the parent is monkey patched after the child is defined, and the child already cached a copy of the parent's __dict__
within its own, everything would break). 将所有内容从父级复制到子级
__dict__
会浪费内存,并且风险值不同步(如果在定义了子级之后父级被猴子修补,并且子级已经在其自身中缓存了父级__dict__
的副本,一切都会破裂)。
You are looking at the __dict__
of the class objects, not of the instances. 您正在查看的是类对象而不是实例的
__dict__
。 If you look at the __dict__
of a Developer
instance, you will see the inherited attributes. 如果查看
Developer
实例的__dict__
,您将看到继承的属性。 Methods (and class attributes) are resolved using the mro
, as discussed at Method Resolution Order (MRO) in new style Python classes . 方法(和类属性)使用
mro
进行解析,如新方法Python类中的“方法解析顺序”(MRO)所述 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.