Sobes.tech
Middle

Comment appeler chacun des méthodes de la classe A ?

sobes.tech IA

Réponse de l'IA

Supposons que nous ayons une classe A avec des méthodes :

import time

class A:
    def what_time(self):
        return f'{time.time()}'

    @property
    def useless_getter(self):
        return self.text

    def __private_or_public(self):
        return 1

    def __str__(self):
        return self.text

    def __init__(self, text):
        self.text = text

Pour appeler chaque méthode :

  • what_time — méthode normale, appelée via une instance :

    a = A('bonjour')
    print(a.what_time())
    
  • useless_getter — propriété, appelée comme un attribut sans parenthèses :

    print(a.useless_getter)
    
  • __private_or_public — méthode avec double underscore, le nom change (name mangling), pour appeler :

    print(a._A__private_or_public())
    
  • __str__ — méthode spéciale, appelée automatiquement lors de la conversion en chaîne :

    print(str(a))
    

Ainsi, pour appeler une méthode privée avec double underscore, il faut utiliser le nom avec la classe : _A__private_or_public().