我有代碼中的所有對象從基礎對象下降,我不打算直接實例化。在我的基礎對象的__init__()
方法中,我試圖執行一些魔術 - 我試圖裝飾或換行,初始化對象的每個方法。但是當我調用結果方法時,我得到的結果令我困惑。下面是示例代碼隔離問題:Python - 爲什麼當我檢查到我返回的對象不是NoneType時,此方法返回NoneType?
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()
產生具有類型NoneType的sis
對象。這裏是輸出:
-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'
這是怎麼發生的?
...相反,它實際上是返回'無',因爲它沒有'return'聲明。 –
martineau