python如何使用神奇的方法为类设置属性';s法
正如上面的代码所示,当我键入print Foo().think.different时,输出将是“think different”。但问题是我应该用魔法的方法得到这个,我该怎么做?谢谢。在类中定义装饰器似乎是一种不必要的复杂方法:python如何使用神奇的方法为类设置属性';s法,python,methods,attributes,Python,Methods,Attributes,正如上面的代码所示,当我键入print Foo().think.different时,输出将是“think different”。但问题是我应该用魔法的方法得到这个,我该怎么做?谢谢。在类中定义装饰器似乎是一种不必要的复杂方法: class Foo(object): def static_var(): def decorator(func): setattr(func, "different", "think dif
class Foo(object):
def static_var():
def decorator(func):
setattr(func, "different", "think different")
return func
return decorator
@static_var()
def think(self):
pass
您可能想看看
\uuu getattr\uuuu()
,它在调用未定义的属性时被调用。或者使用\uuu getattribute\uuuu()
,这是为所有属性调用的。。调用必需的属性时,使其返回方法。这是我想你需要的
class Foo(object):
def think(self):
pass
setattr(think, "different", "think different")
print(Foo().think.different)
小心使用
\uuu getattribute\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。因此,您可以设置一个指向类方法的属性。
class A(object):
def __init__(self):
pass
def printer(self,input):
print(input)
def __getattr__(self,atr):
if atr == 'methd':
return self.printer