Middle
Come chiamare ciascun metodo della classe A?
sobes.tech AI
Risposta dell'AI
Supponiamo di avere una classe A con metodi:
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
Per chiamare ogni metodo:
-
what_time— metodo normale, chiamato tramite un'istanza:a = A('ciao') print(a.what_time()) -
useless_getter— proprietà, chiamata come attributo senza parentesi:print(a.useless_getter) -
__private_or_public— metodo con doppio underscore, il nome cambia (name mangling), per chiamare:print(a._A__private_or_public()) -
__str__— metodo speciale, chiamato automaticamente durante la conversione in stringa:print(str(a))
Quindi, per chiamare un metodo privato con doppio underscore, bisogna usare il nome con la classe: _A__private_or_public().