Heim  >  Fragen und Antworten  >  Hauptteil

python3,定制类,getattr相关用法

class Chain(object):
    def __init__(self,path=""):
        self._path = path
    def __getattr__(self,path):
        return Chain("%s/%s" %(self._path,path))
    def __call__(self,path):
        return Chain("%s/%s" %(self._path,path))
    def __str__(self):
        return self._path
    __repr__ = __str__
    
print(Chain().a.b.user("Michael").c.d)

看了好久还是理解不了这语句,如能详述一些细节,感激不尽

PHP中文网PHP中文网2717 Tage vor493

Antworte allen(1)Ich werde antworten

  • PHPz

    PHPz2017-04-18 10:27:47

    getattr(object, name[, default])

    
    class Student(object):
        def __init__(self):
            self.name = 'Michael'
        def __getattr__(self,attr):
            return attr
    
            
    s = Student()
    s.name 
        --> 'Michael'
    s.score    
        -->  'score'
        

    _getattr__是python里的一个内建函数,动态返回一个属性
    当调用不存在的属性时,Python会试图调用__getattr__(self,'score')来获取属性,并且返回score

    __str__用于打印函数
    __call__把类当做类似函数一样调用

    代码执行流程:
    Chain()创建一个实例,并且 path初始默认为 "" ,Chain().a 时,类中并没有 a 属性,Python解析器调用 getattr函数 --> __getattr__(self,path='a'),
    并返回一个Chain实例,然后把/a 赋值gei path 传入,继续b,因为同样没有b 属性,执行getattr函数,将/a/b传入,
    然后.user(“Michael”),先会执行getattr返回Chain实例,但是因为有()括号在,所以返回的是Chain(),
    这个就会调用call函数了,然后把“ChenTian”作为path传入,然后call函数就返回了/a/b/user/ChenTian,剩下的类同。

    .user("Michael”) 刚开始的user被getattr函数捕获,并返回Chain(),然后再执行__call__来调用 "Michael"
    
    

    代码流程图

    Antwort
    0
  • StornierenAntwort