मेरे पास एक ऑब्जेक्ट पदानुक्रम है जिसमें लगभग सभी विधियां कक्षा विधियां हैं।पायथन - क्या मैं क्लास उदाहरण से वर्ग विधियों को प्रोग्रामेटिक रूप से सजाने सकता हूं?
class ParentObject(object):
def __init__(self):
pass
@classmethod
def smile_warmly(cls, the_method):
def wrapper(kls, *args, **kwargs):
print "-smile_warmly - "+kls.__name__
the_method(*args, **kwargs)
return wrapper
@classmethod
def greetings(cls):
print "greetings"
class SonObject(ParentObject):
@classmethod
def hello_son(cls):
print "hello son"
@classmethod
def goodbye(cls):
print "goodbye son"
class DaughterObject(ParentObject):
@classmethod
def hello_daughter(cls):
print "hello daughter"
@classmethod
def goodbye(cls):
print "goodbye daughter"
if __name__ == '__main__':
son = SonObject()
son.greetings()
son.hello_son()
son.goodbye()
daughter = DaughterObject()
daughter.greetings()
daughter.hello_daughter()
daughter.goodbye()
कोड दिया आउटपुट के रूप में निम्नलिखित:
greetings
hello son
goodbye son
greetings
hello daughter
goodbye daughter
मैं चाहूँगा उत्पादन के लिए कोड का पालन:
-smile_warmly - SonObject
greetings
-smile_warmly - SonObject
hello son
-smile_warmly - SonObject
goodbye son
-smile_warmly - DaughterObject
greetings
-smile_warmly - DaughterObject
hello daughter
-smile_warmly - DaughterObject
goodbye daughter
लेकिन मुझे नहीं पता यह निम्नलिखित की तरह दिखता है प्रत्येक विधि से पहले लाइन @smile_warmly
जोड़ना चाहते हैं (और जब मैं ऊपर करने के लिए कि कोड में प्रयास करते हैं, तो मुझे त्रुटि संदेश TypeError: 'classmethod' object is not callable
मिल)। इसके बजाय, मैं __init__()
विधि में प्रोग्रामेटिक रूप से प्रत्येक विधि की सजावट करना चाहता हूं।
क्या यह संभव है प्रोग्राम के रूप में अजगर में तरीकों को सजाने के लिए?
EDIT: कुछ ऐसा लगता है जो काम करने लगता है - नीचे मेरा उत्तर देखें। ब्रेनबर्न के लिए धन्यवाद।
आप परिचित metaclasses की अवधारणा है? –
लगता है जैसे आप इसे देखना चाहते हैं: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python शायद अगर आप इस लड़के को सजावटी का उपयोग करने पर भी सेट कर रहे हैं: http://stackoverflow.com/questions/739654/understanding-python-decorators –
मैंने उनके बारे में सुना है, लेकिन यह इसके बारे में है। तो नहीं। – jononomo