我對運行下面的代碼的行爲有兩個問題。爲什麼__new__
甚至沒有實例化對象而被調用?我認爲__new__
控制了新的實例的創建。接下來,爲什麼delattr
增加AttributeErrorhasattr
返回真對於大小?Python __new__繼承的元類行爲
class ShapeBase(type):
def __new__(cls, name, bases, attrs):
rv = super(ShapeBase, cls).__new__(cls, name, bases, attrs)
parents = [base for base in bases if isinstance(base, ShapeBase)]
# don't do anything unless this is a subclass of Shape
if not parents:
return rv
print hasattr(rv, 'altitude') # prints True
print rv.altitude # prints 7
del rv.altitude # deletes altitude from rv
print hasattr(rv, 'size') # prints True
print rv.size # prints 5
delattr(rv, 'size') # raises AttributeError
return rv
class Shape(object):
__metaclass__ = ShapeBase
size = 5
class Triangle(Shape):
altitude = 7
您的評論「除非這是Shape的子類,否則不要做任何事情」是誤導性的,因爲您正在做什麼,您是否在檢查它是否屬於ShapeBase類的元類。實際上,「Shape」不是「Shape的子類」(儘管'issubclass(Shape,Shape)== True'),而「Triangle」是。因此,代碼可能應該是這樣,但如果評論根本不存在,那麼它就不那麼令人困惑了。 –