Last active
May 18, 2016 19:57
-
-
Save khornberg/9735eda92a14006bc91a935eb2268c93 to your computer and use it in GitHub Desktop.
Python subclass determined at runtime
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
# Based on http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Metaprogramming.html | |
class P1(object): | |
name = 'Parent1' | |
class P2(object): | |
name = 'Parent2' | |
K = 'P1' | |
class MetaBase(type): | |
def __new__(mcl, name, bases, nmspc): | |
return super(MetaBase, mcl).__new__(mcl, name, bases, nmspc) | |
class Meta(MetaBase): | |
def __new__(mcl, name, bases, nmspc): | |
bases = (P1,) if K is 'P1' else (P2,) | |
return super(Meta, mcl).__new__(mcl, name, bases, nmspc) | |
class C(object): | |
__metaclass__ = Meta | |
c = C() | |
print(c.__class__.__bases__, c.__class__) # ((<class '__main__.P1'>,), <class '__main__.C'>) | |
print(c.name) # Parent1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment