python3,定制类,getattr相关用法
PHP中文网
PHP中文网 2017-04-18 10:25:47
0
1
518
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中文网

认证高级PHP讲师

reply all(1)
PHPzhong

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__ is a built-in function in python that dynamically returns an attribute
When calling a non-existent attribute, Python will try to call __getattr__(self,'score') to get the attribute and return score

__str__ is used to print functions
__call__ calls the class as a similar function

Code execution process:
Chain() creates an instance, and the path initially defaults to "". When Chain().a, there is no a attribute in the class, and the Python parser calls the getattr function --> __getattr__(self,path ='a'),
and return a Chain instance, then pass in /a assignment gei path, continue with b, because there is no b attribute, execute the getattr function, pass /a/b in,
then .user(" Michael"), it will first execute getattr to return the Chain instance, but because there are () brackets, it will return Chain(),
This will call the call function, and then pass "ChenTian" as the path, and then call the function /a/b/user/ChenTian is returned, and the rest is similar.

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

Code flow chart

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!