यहां नया। इसके अलावा मैं पाइथन के लिए नया (बहुत) नया हूं और निम्नलिखित व्यवहार को समझने की कोशिश कर रहा हूं। क्या कोई मुझे समझा सकता है कि इस उदाहरण में दो तरीकों के अलग-अलग आउटपुट क्यों हैं?पायथन सजावट और विधियां
def map_children(method):
def wrapper(self,*args,**kwargs):
res = method(self,*args,**kwargs)
for child in self._children:
method(child,*args,**kwargs)
return res
return wrapper
class Node(object):
def __init__(self,name,parent=None):
self._namestring = name
if parent:
self._parent = parent
self._children = []
@map_children
def decorated(self):
if hasattr(self,'_parent'):
print '%s (child of %s)'%(self._namestring,self._parent._namestring)
else:
print '%s'% self._namestring
def undecorated(self):
if hasattr(self,'_parent'):
print '%s (child of %s)'%(self._namestring,self._parent._namestring)
else:
print '%s'% self._namestring
for child in self._children:
child.undecorated()
def runme():
parent = Node('parent')
child1 = Node('child1',parent)
child2 = Node('child2',parent)
grandchild = Node('grandchild',child1)
child1._children.append(grandchild)
parent._children.append(child1)
parent._children.append(child2)
print '**********result from decorator**********'
parent.decorated()
print '**********result by hand**********'
parent.undecorated()
यहाँ मेरी सिस्टम पर उत्पादन होता है:
In[]:testcase.runme() **********result from decorator********** parent child1 (child of parent) child2 (child of parent) **********result by hand********** parent child1 (child of parent) grandchild (child of child1) child2 (child of parent)
तो क्यों सजाया कॉल कभी नहीं पोता नोड के लिए उतरना है? मैं स्पष्ट रूप से वाक्य रचना के बारे में कुछ याद कर रहा हूँ ...
धन्यवाद! पता था कि ऐसा कुछ होना था। मैंने @ नोटेशन के साथ यह कोशिश की लेकिन यह काम नहीं किया (जाहिर है), और मुझे सही वाक्यविन्यास नहीं मिला। तब मैं खुद को मनाने में कामयाब रहा कि यह वास्तविक विधि को बदल रहा था, इसलिए कोई फर्क नहीं पड़ता। मुझे इसे "उचित" मैक्रोज़ की तरह सोचना बंद करना होगा। –
मुझे लगता है कि यह दृष्टिकोण ऐसा नहीं करेगा जो आप उम्मीद करते हैं कि नोड उप-वर्गीकृत है और सबक्लास के पास विधि का अपना संस्करण है ... – simon