Python 相互分配方法是如何工作的?(“调用”=“获取属性”)
我只知道给变量赋值,但在这种情况下,给另一个方法赋值?这到底是怎么回事 下面的代码行是做什么的?这种用法有名字吗Python 相互分配方法是如何工作的?(“调用”=“获取属性”),python,Python,我只知道给变量赋值,但在这种情况下,给另一个方法赋值?这到底是怎么回事 下面的代码行是做什么的?这种用法有名字吗 __repr__ = __str__ __call__ = __getattr__ 示例1 class Chain(object): def __init__(self,path=''): print("Constructor.") self.__path=path def __getattr__(self,path): print("getattr
__repr__ = __str__
__call__ = __getattr__
示例1
class Chain(object):
def __init__(self,path=''):
print("Constructor.")
self.__path=path
def __getattr__(self,path):
print("getattr method called. path: %s" % path)
return Chain(self.__path+'/'+path)
def __str__(self):
print("String metod called %s" % self.__path)
return self.__path
# This part runs before init!
print("Weird statements.")
__repr__=__str__
__call__=__getattr__
if __name__ == '__main__':
c = Chain()
## Print function calls __call__ and __getattr__ methods, first getattr for 'users' attribute, then 'calls' for 'michael' string argument.
print(c.users("Michael"))
输出:
Weird statements.
Constructor.
getattr method called. path: users
Constructor.
getattr method called. path: Michael
Constructor.
String metod called /users/Michael
/users/Michael
- c、 用户#调用getattr方法
- c、 用户('michael')#调用调用方法,但如何调用呢
__repr__ = __str__
__call__ = __getattr__
没有名字,因为没有什么特别的。它只是将一个变量分配给另一个变量\uuuu repr\uuuu=\uuuu str\uuuu
与b=a
完全相同,它只是创建了对同一对象的第二个引用(使用不同的名称)
“魔力”在于Python的类主体基本上是一个函数,它的代码是按顺序执行的,最后所有的“局部变量”都被收集并传递给类构造函数(不要与类的构造函数混淆),成为类的属性,这就是Python中的方法。但在最后一步之前,执行的只是代码
t由于\uuuu str\uuuuuuu
委托给\uuuu repr\uuuuuu
,因此,如果您希望两者都是同一事物,那么这个特定的分配也是无用的(或者更恰当地说是错误的方式)
除此之外:
这是非常糟糕的风格,你不应该使用它。Python中的名称损坏是由于与继承相关的原因而存在的,它们与“信息隐藏”无关,也不是创建“私有成员”的方法。如果要指定成员为“private”,则约定使用单个下划线前缀