generators as decorators simple issue
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Wed Sep 12 02:08:02 EDT 2012
Am 12.09.2012 04:28 schrieb j.m.dagenhart at gmail.com:
> I'm trying to call SetName on an object to prevent me from ever having to call it explictly again on that object. Best explained by example.
>
>
> def setname(cls):
> '''this is the proposed generator to call SetName on the object'''
> try:
> cls.SetName(cls.__name__)
> finally:
> yield cls
>
>
> class Trial:
> '''class to demonstrate with'''
> def SetName(self, name):
> print 1, 1
>
> @setname
> class Test(Trial):
> '''i want SetName to be called by using setname as a decorator'''
> def __init__(self):
>
> print 'Yay! or Invalid.'
>
> if __name__ == '__main__':
> test = Test()
>
>
> How can i fix this?
I am not sure what exactly you want to achieve, but I see 2 problems here:
1. Your setname operates on a class, but your SetName() is an instance
function.
2. I don't really understand the try...finally yield stuff. As others
already said, you probably just want to return. I don't see what a
generator would be useful for here...
def setname(cls):
'''this is the proposed generator to call SetName on the object'''
try:
cls.SetName(cls.__name__)
finally:
return cls
and
class Trial(object):
'''class to demonstrate with'''
@classmethod
def SetName(cls, name):
print 1, 1
should solve your problems.
More information about the Python-list
mailing list