-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmetaClasses.py
More file actions
57 lines (35 loc) · 1.01 KB
/
metaClasses.py
File metadata and controls
57 lines (35 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Uses for metaclasses
#
# Register a class on definition
# Initialise attributes (Usually to set a name)
# Modify a class based on its definition
# Ensure subclasses implemention
# Totally mess with the way a class behaves
# class Car:
# def __init__(self, color):
# self.color = color
# def drive(self):
# print("You are driving the car")
def init_func(self, color):
self._color = color
def drive(self):
print("You are driving the car")
Car = type("Car", (object,), {"__init__": init_func, "drive": drive})
my_car = Car("red")
my_car.drive()
# A metaClass is a callable which returns a class
# A function as a metaclass
# def stupid_metaclass(classname, bases, attrdict):
# return type(classname, bases, attrdict)
# class MyClass(metaclass=stupid_metaclass):
# pass
class MyMeta(type):
pass
class MyClass(metaclass=MyMeta):
pass
instance = MyClass()
# >>> type(instance)
# <class '__main__.MyClass'>
# >>> type(MyClass)
# <class '__main__.MyMeta'>
# >>>