我有下面的代码片段,它有两个方法func_norule((和func_with_rule(。方法func_with_rule((使用@rule进行装饰,其中as func_norule(((没有任何装饰符。
当我使用getattr函数时,fn=getattr(self,'func_norule'(返回函数,其中作为fn=getatt(selve,'func_with_rule'([/em>返回None。
为什么使用装饰器和不使用装饰器时会有不同的行为?有解决这个问题的方法吗?
class Student():
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
## Decorator function to decorate all the rules function
def rule(func):
print(func.__name__)
def func_norule(self):
#This method works with getattr
print("func_norule:" + self.name)
@rule
def func_with_rule(self):
#This method returns None with getattr
print("func_with_rule:" + self.name)
def myFunc2(self):
fn = getattr(self, 'func_norule')
fn()
fn = getattr(self, 'func_with_rule')
fn()
student = Student('myName', 8)
student.myFunc2()
这是因为您没有在装饰器中绑定self
。您可以更改装饰器,以便self
参数将传递给您的装饰方法:
class Student:
# ...
def rule(func):
def _(self, *args, **kwargs):
print("Before calling", func.__name__)
result = func(self, *args, **kwargs)
print("After calling", func.__name__)
return result
return _
# ...
@rule
def func_with_rule(self):
#This method returns None with getattr
print("func_with_rule:" + self.name)
现在,当你做
student = Student('myName', 8)
student.myFunc2()
输出
func_norule:myName
Before calling func_with_rule
func_with_rule:myName
After calling func_with_rule