Created
June 2, 2014 04:27
-
-
Save hanks/a219f744c09b570bb7be to your computer and use it in GitHub Desktop.
dynamic inherits class
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
class A(object): | |
def __init__(self): | |
print 'A init' | |
@classmethod | |
def foo(cls): | |
print 'A foo' | |
def bar(self): | |
print 'A bar' | |
class B(object): | |
def __init__(self): | |
print 'B init' | |
@classmethod | |
def foo(cls): | |
print 'B foo' | |
def bar(self): | |
print 'B bar' | |
import random | |
def get_random_key(): | |
return random.choice(['A', 'B']) | |
class AttrType(type): | |
def __new__(meta, name, bases, dct): | |
klass_key = get_random_key() | |
klass = None | |
if klass_key == 'A': | |
klass = A | |
elif klass_key == 'B': | |
klass = B | |
bases = list(bases) | |
bases.insert(0, klass) | |
bases = tuple(bases) | |
return super(AttrType, meta).__new__(meta, name, bases, dct) | |
class MyClass(object): | |
__metaclass__ = AttrType | |
if __name__ == '__main__': | |
MyClass.foo() | |
obj = MyClass() | |
obj.bar() | |
obj = MyClass() | |
obj.bar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment