Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Created January 6, 2019 17:37
Show Gist options
  • Save x-yuri/243dc86c6b4fdbb78ec7576f18bf03c8 to your computer and use it in GitHub Desktop.
Save x-yuri/243dc86c6b4fdbb78ec7576f18bf03c8 to your computer and use it in GitHub Desktop.
python: substituting class
class A:
qux = 'A'
def __init__(self, name):
self.name = name
def foo(self):
print('foo')
class B:
qux = 'B'
def bar(self):
print('bar')
a = A('a')
print(a.__class__) # <class '__main__.A'>
print(a.__dict__) # {'name': 'a'}
print(a.qux) # A
a.foo() # foo
a.__class__ = B
print(a.__class__) # <class '__main__.B'>
print(a.__dict__) # {'name': 'a'}
print(a.qux) # B
# a.foo() # AttributeError: 'B' object has no attribute 'foo'
a.bar() # bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment