Skip to content

Instantly share code, notes, and snippets.

@ustropo
Created February 4, 2023 11:09
Show Gist options
  • Save ustropo/60af9b2a83d138c4d1ec40116bdb9b43 to your computer and use it in GitHub Desktop.
Save ustropo/60af9b2a83d138c4d1ec40116bdb9b43 to your computer and use it in GitHub Desktop.
class DogMeta(type):
def __new__(cls, name, bases, dct):
print(f">> DogMeta __new__: {name}")
print(f">> DogMeta __new__: {bases}")
print(f">> DogMeta __new__: {dct}")
x = super().__new__(cls, name, bases, dct)
x.race = "Dog"
return x
class Dog(metaclass=DogMeta):
def init(self, name) -> None:
print(f"Dog init -> {name}")
self.name = name
def bark(self) -> None:
print(f"Dog bark! {self.name}")
d = Dog()
d.init("Rex")
d.bark()
OtherDog = DogMeta("OtherDog", (), {"name": "OtherRex"})
od = OtherDog()
print(od.name, od.race)
##
# >> DogMeta __new__: Dog
# >> DogMeta __new__: ()
# >> DogMeta __new__: {'__module__': '__main__', '__qualname__': 'Dog', 'init': <function ...>, 'bark': <function ...>}
# Dog init -> Rex
# Dog bark! Rex
# >> DogMeta __new__: OtherDog
# >> DogMeta __new__: ()
# >> DogMeta __new__: {'name': 'other'}
# other Dog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment