Skip to content

Instantly share code, notes, and snippets.

@jpclipffel
Last active June 11, 2018 09:21
Show Gist options
  • Save jpclipffel/44db865dd15170fcb8b81ad188b53cbb to your computer and use it in GitHub Desktop.
Save jpclipffel/44db865dd15170fcb8b81ad188b53cbb to your computer and use it in GitHub Desktop.
Example of Python's __new__ used in conjunction with inheritance
import sys
class Root:
# Derived class references.
# As the classes Alpha and Beta are not already defined, their names are
# stored instead of their reference ("Alpha" instead of Alpha).
__derived = {
"alpha": {"class": "Alpha", "count": 0},
"beta": {"class": "Beta", "count": 0}
}
def __new__(cls, derived_name, *args, **kwargs):
print("Root.__new__(cls={}, derived_name={}, *args={})".format(cls, derived_name, args))
if derived_name in cls.__derived:
cls.__derived[derived_name]["count"] += 1
return object.__new__(getattr(sys.modules[__name__], cls.__derived[derived_name]["class"]))
else:
raise Exception("Invalid derived_name. Requires one of {}".format(", ".join(data.keys())))
def __init__(self, token, *args, **kwargs):
print("Root.__init__(self={}, token={})".format(self, token))
self.token = token
@classmethod
def count(cls, derived_name):
return cls.__derived[derived_name]["count"]
class Alpha(Root):
def __init__(self, *args):
print("Alpha.__init__(self={}, *args={})".format(self, args))
super().__init__("alpha_token")
def foo(self):
print("Alpha.foo(): token = {}".format(self.token))
class Beta(Root):
def __init__(self, *args):
print("Beta.__init__(self={}, *args={})".format(self, args))
super().__init__("beta_token")
def foo(self):
print("Beta.foo(): token = {}".format(self.token))
if __name__ == "__main__":
i, j = Root("alpha"), Root("beta")
i.foo()
j.foo()
print("alphas: {}".format(Root.count("alpha")))
print("betas: {}".format(Root.count("beta")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment