Maison  >  Questions et réponses  >  le corps du texte

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 Il y a quelques jours498

répondre à tous(1)je répondrai

  • PHPz

    PHPz2017-04-18 10:27:47

    getattr(objet, nom[, par défaut])

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

    _getattr__ est une fonction intégrée à Python, qui renvoie dynamiquement un attribut
    Lors de l'appel d'un attribut inexistant, Python essaiera d'appeler __getattr__(self,'score') pour obtenir l'attribut et renvoyer le score

    __str__ est utilisé pour imprimer des fonctions
    __call__ appelle la classe comme une fonction similaire

    Flux d'exécution du code :
    Chain() crée une instance et le chemin est initialement par défaut "". Lorsque Chain().a, il n'y a pas d'attribut dans la classe et l'analyseur Python appelle la fonction getattr. --> __getattr__ (self,path='a'),
    et renvoie une instance de chaîne, puis passe /a assign gei path in, continue b, car il n'y a pas d'attribut b, exécute la fonction getattr, passe / a/b in,
    Ensuite, .user("Michael") exécutera d'abord getattr pour renvoyer l'instance de Chain, mais comme il y a des crochets (), Chain() est renvoyé
    Cela appellera la fonction d'appel, puis " ChenTian " est transmis comme chemin, puis la fonction d'appel renvoie /a/b/user/ChenTian, ​​​​et le reste est similaire.

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

    Organigramme du code

    répondre
    0
  • Annulerrépondre