-
Notifications
You must be signed in to change notification settings - Fork 0
/
metaclass.py
57 lines (42 loc) · 1.39 KB
/
metaclass.py
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
def bark(self):
print('Woof, woof')
class Animal:
def feed(self):
print('It is feeding time!')
Dog = type('Dog', (Animal, ), {'age':0, 'bark':bark})
print('The class name is:', Dog.__name__)
print('The class is an instance of:', Dog.__class__)
print('The class is based on:', Dog.__bases__)
print('The class attributes are:', Dog.__dict__)
doggy = Dog()
doggy.feed()
doggy.bark()
#===========================#
#own meta class
class My_Meta(type):
def __new__(mcs, name, bases, dictionary):
obj = super().__new__(mcs, name, bases, dictionary)
obj.custom_attribute = 'Added by My_Meta'
return obj
class My_Object(metaclass=My_Meta):
pass
print(My_Object.__dict__)
#===========================#
def greetings(self):
print('Just a greeting function, but it could be something more serious like a check sum')
class My_Meta(type):
def __new__(mcs, name, bases, dictionary):
if 'greetings' not in dictionary:
dictionary['greetings'] = greetings
obj = super().__new__(mcs, name, bases, dictionary)
return obj
class My_Class1(metaclass=My_Meta):
pass
class My_Class2(metaclass=My_Meta):
def greetings(self):
print('We are ready to greet you!')
myobj1 = My_Class1()
myobj1.greetings()
myobj2 = My_Class2()
myobj2.greetings()
#===========================#