From 8869d5ba5a3d6987b7133a8e994a56b6fd7f45d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Ot=C3=A1vio?= Date: Tue, 29 Nov 2022 10:23:00 -0300 Subject: [PATCH] =?UTF-8?q?C=C3=B3digo:=20Metaclasses=20s=C3=A3o=20o=20tip?= =?UTF-8?q?o=20das=20classes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aula155.py | 51 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/aula155.py b/aula155.py index 5eac407..45f5a62 100644 --- a/aula155.py +++ b/aula155.py @@ -22,14 +22,47 @@ # com certeza que precisam delas e não precisam de uma explicação # sobre o porquê)." # — Tim Peters (CPython Core Developer) - -# object acima -# class Foo: -# ... +def meu_repr(self): + return f'{type(self).__name__}({self.__dict__})' -Foo = type('Foo', (object,), {}) -f = Foo() -# print(isinstance(f, Foo)) -print(type(f)) -print(type(Foo)) +class Meta(type): + def __new__(mcs, name, bases, dct): + print('METACLASS NEW') + cls = super().__new__(mcs, name, bases, dct) + cls.attr = 1234 + cls.__repr__ = meu_repr + + if 'falar' not in cls.__dict__ or \ + not callable(cls.__dict__['falar']): + raise NotImplementedError('Implemente falar') + + return cls + + def __call__(cls, *args, **kwargs): + instancia = super().__call__(*args, **kwargs) + + if 'nome' not in instancia.__dict__: + raise NotImplementedError('Crie o attr nome') + + return instancia + + +class Pessoa(metaclass=Meta): + # falar = 123 + + def __new__(cls, *args, **kwargs): + print('MEU NEW') + instancia = super().__new__(cls) + return instancia + + def __init__(self, nome): + print('MEU INIT') + # self.nome = nome + + def falar(self): + print('FALANDO...') + + +p1 = Pessoa('Luiz') +p1.falar()