Вот пример того, что я имею в виду:
class MyDecorator(object):
def __call__(self, func):
# At which point would I be able to access the decorated method's parent class's instance?
# In the below example, I would want to access from here: myinstance
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
class SomeClass(object):
##self.name = 'John' #error here
name="John"
@MyDecorator()
def nameprinter(self):
print(self.name)
myinstance = SomeClass()
myinstance.nameprinter()
Я должен украсить фактический класс?
class MyDecorator(object):
def __call__(self, func):
def wrapper(that, *args, **kwargs):
## you can access the "self" of func here through the "that" parameter
## and hence do whatever you want
return func(that, *args, **kwargs)
return wrapper
Обратите внимание в этом контексте, что использование «self» является просто соглашением, метод просто использует первый аргумент как ссылку на объект-экземпляр:
class Example:
def __init__(foo, a):
foo.a = a
def method(bar, b):
print bar.a, b
e = Example('hello')
e.method('world')
Я думаю, что lambdaj имеет особенности для такого рода вещей.
-121--4817694-В JDK - нет. Есть в apache commons-lang :
ClassUtils.toClass (Object [] objects)
Но писать его самому совсем не больно.
-121--4817693- Аргумент self передается в качестве первого аргумента. Кроме того, MyDecorator
является классом, эмулирующим функцию. Проще сделать его фактической функцией.
def MyDecorator(method):
def wrapper(self, *args, **kwargs):
print 'Self is', self
return method(self, *args, **kwargs)
return wrapper
class SomeClass(object):
@MyDecorator
def f(self):
return 42
print SomeClass().f()