Skip to content

Instantly share code, notes, and snippets.

@SahbiOuali13
Last active May 20, 2022 20:23
Show Gist options
  • Save SahbiOuali13/a7c7efa44695c112b3a583bf51dbf8aa to your computer and use it in GitHub Desktop.
Save SahbiOuali13/a7c7efa44695c112b3a583bf51dbf8aa to your computer and use it in GitHub Desktop.
These are some usecases: - Subclassing immutable Built-in types - Returning another class - Allowing a single instance in your class - Partially Emulating collections.namedtuple
class Person:
def __new__(cls, *args, **kwargs):
print('The instance is being constructed')
return super().__new__(cls)
def __init__(self, value):
print('The instance is being initialized')
self.value = value
if __name__ == '__main__':
p1 = Person("Samir")

Subclassing immutable Built-in types

class Distance(float):
    def __new__(cls, value, unit):
        instance = super().__new__(cls, value)
        instance.unit = unit
        return instance
   
        
d = Distance(5.0, 'meters')
print(d.unit)

Returning Instances of a Different Class

from random import choice


class Pet:
    def __new__(cls):
        other = choice([Dog, Cat, Python])
        instance = super().__new__(other)
        print(f"I'am a {type(instance).__name__}!")
        return instance
    
    def __init__(self):
        print('Never runs!')
        
class Dog:
    def communicate(self):
        print('woof! woof!')
        
class Cat:
    def communicate(self):
       print('meow! meow!')
    
class Python:
    def communicate(self):
        print('hiss! hiss!')

# Getting a random class at each call of the class
animal = Pet()
animal.communicate()

Allowing a single instance in your class (singleton)

class Singleton(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance


first = Singleton()
second = Singleton()
print(first is second)  # True

Partially Emulating collections.namedtuple

<!--too complicated-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment