Skip to content

Instantly share code, notes, and snippets.

@hanks
Created June 2, 2014 03:46
Show Gist options
  • Save hanks/42bf4106aa3343f6ba88 to your computer and use it in GitHub Desktop.
Save hanks/42bf4106aa3343f6ba88 to your computer and use it in GitHub Desktop.
implement __getattr__ in both class and instance
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
def __init__(self, key):
print 'A key', key
@classmethod
def foo(cls):
print 'A foo'
def bar(self):
print 'A bar'
class B(object):
def __init__(self, key):
print 'A key', key
@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 __init__(cls, name, bases, dict):
key = get_random_key()
if key == 'A':
cls.klass = A
elif key == 'B':
cls.klass = B
super(AttrType, cls).__init__(name, bases, dict)
def __getattr__(cls, name):
return getattr(cls.klass, name)
class MyClass(object):
__metaclass__ = AttrType
def __init__(self, key):
if key == 'A':
self.obj = A(key)
elif key == 'B':
self.obj = B(key)
def __getattr__(self, name):
return getattr(self.obj, name)
if __name__ == '__main__':
MyClass.foo()
obj = MyClass('A')
obj.bar()
obj = MyClass('B')
obj.bar()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment