我有代码,其中所有对象都来自一个基础对象,我不打算直接实例化它。在__init__()
我的基础对象的方法中,我试图执行一些魔法——我试图装饰或包装正在初始化的对象的每个方法。但是当我调用结果方法时,我得到的结果让我感到困惑。这是隔离问题的示例代码:
class ParentObject(object):
def __init__(self):
self._adjust_methods(self.__class__)
def _adjust_methods(self, cls):
for attr, val in cls.__dict__.iteritems():
if callable(val) and not attr.startswith("_"):
setattr(cls, attr, self._smile_warmly(val))
bases = cls.__bases__
for base in bases:
if base.__name__ != 'object':
self._adjust_methods(base)
def _smile_warmly(self, the_method):
def _wrapped(cls, *args, **kwargs):
print "\n-smile_warmly - " +cls.__name__
the_method(self, *args, **kwargs)
cmethod_wrapped = classmethod(_wrapped)
return cmethod_wrapped
class SonObject(ParentObject):
def hello_son(self):
print "hello son"
def get_sister(self):
sis = DaughterObject()
print type(sis)
return sis
class DaughterObject(ParentObject):
def hello_daughter(self):
print "hello daughter"
def get_brother(self):
bro = SonObject()
print type(bro)
return bro
if __name__ == '__main__':
son = SonObject()
son.hello_son()
daughter = DaughterObject()
daughter.hello_daughter()
sis = son.get_sister()
print type(sis)
sis.hello_daughter()
bro = sis.get_brother()
print type(bro)
bro.hello_son()
然而,程序崩溃了——该行sis = son.get_sister()
导致sis
对象的类型为 NoneType。这是输出:
-smile_warmly - SonObject
hello son
-smile_warmly - DaughterObject
hello daughter
-smile_warmly - SonObject
<class '__main__.DaughterObject'>
<type 'NoneType'>
Traceback (most recent call last):
File "metaclass_decoration_test.py", line 48, in <module>
sis.hello_daughter()
AttributeError: 'NoneType' object has no attribute 'hello_daughter'
为什么会这样?