Last active
September 24, 2019 01:12
-
-
Save cybaj/d2918f23136aa78bdf334230a2bdb0ab to your computer and use it in GitHub Desktop.
In Python, 'class' is also object
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
""" | |
referenced from https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python/6581949#6581949 | |
""" | |
""" | |
1. | |
""" | |
def choose_class(name): | |
if name == 'foo': | |
class Foo(object): | |
pass | |
return Foo | |
else: | |
class Bar(object): | |
pass | |
return Bar | |
MyClass = choose_class('foo') | |
print(MyClass) # >>> <class '__main__.Foo'> | |
print(MyClass()) # >>> <__main__.Foo object at 0x89c6d4c> | |
""" | |
2. | |
""" | |
Foo = type('Foo', (), {'aa':True}) # return Class Object | |
# this is same as... | |
class MyShinyClass(object): | |
bar = True | |
pass | |
def choose_class_2(name): | |
if name == 'foo': | |
Foo = type('Foo', (), {'aa':True}) # return Class Object | |
return Foo | |
else: | |
Bar = type('Bar', (), {'bar':True}) # return Class Object | |
return Bar | |
MyShinyClass = choose_class_2('foo') | |
print(MyShinyClass) # >>> <class '__main__.MyShinyClass'> | |
print(MyShinyClass()) # >>> <__main__.MyShinyClass object at 0x8997cec> | |
""" | |
type(name of the class, | |
tuple of the parent class (for inheritance, can be empty), | |
dictionary containing attributes names and values) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment