__new__ e __init__ em classes Python

This commit is contained in:
Luiz Otávio
2022-11-19 19:09:44 -03:00
parent 09c205cf15
commit 28cc7f2ea4
2 changed files with 25 additions and 6 deletions

View File

@@ -1,7 +1,3 @@
from eletronico import Smartphone
conta_1 = ((1 + 1) ** (5 + 5))
galaxy_s = Smartphone('Galaxy S')
iphone = Smartphone('iPhone')
galaxy_s.ligar()
iphone.desligar()
print(conta_1)

23
aula148.py Normal file
View File

@@ -0,0 +1,23 @@
# __new__ e __init__ em classes Python
# __new__ é o método responsável por criar e
# retornar o novo objeto. Por isso, new recebe cls.
# __new__ ❗DEVE retornar o novo objeto❗
# __init__ é o método responsável por inicializar
# a instância. Por isso, init recebe self.
# __init__ ❗NÃO DEVE retornar nada (None)❗️
# object é a super classe de uma classe
class A:
def __new__(cls, *args, **kwargs):
instancia = super().__new__(cls)
return instancia
def __init__(self, x):
self.x = x
print('Sou o init')
def __repr__(self):
return 'A()'
a = A(123)
print(a.x)