You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
These are some usecases:
- Subclassing immutable Built-in types
- Returning another class
- Allowing a single instance in your class
- Partially Emulating collections.namedtuple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fromrandomimportchoiceclassPet:
def__new__(cls):
other=choice([Dog, Cat, Python])
instance=super().__new__(other)
print(f"I'am a {type(instance).__name__}!")
returninstancedef__init__(self):
print('Never runs!')
classDog:
defcommunicate(self):
print('woof! woof!')
classCat:
defcommunicate(self):
print('meow! meow!')
classPython:
defcommunicate(self):
print('hiss! hiss!')
# Getting a random class at each call of the classanimal=Pet()
animal.communicate()
Allowing a single instance in your class (singleton)