-
Notifications
You must be signed in to change notification settings - Fork 0
/
Metaclass_example_01.py
42 lines (33 loc) · 1.26 KB
/
Metaclass_example_01.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
#############################################################################
#
# The metaclass complains if a class implements two methods, one of each is
# __init__
#
# Inspired by Jack Diederich's talk:
# https://www.youtube.com/watch?v=o9pEzgHorH0
#
class JackDmeta(type):
def __init__(self, name, bases, attrs):
# collect the methods in a list
print(bases)
methods = []
for item, value in attrs.items():
if hasattr(value, "__call__"):
methods.append(value.__name__)
# check if Jack D. is pissed off
if ('__init__' in methods) and len(methods) == 2:
errorstr = ('This is not a proper class!' +
' It only has two methods, one of which' +
' is __init__. Do you even Python idiomatically?!')
raise TypeError(errorstr)
# The following class can not even be defined without throwing an exception
class MyRedundantclass(class=Metaclass):
"""
A prime example of a redundant class; just a half-hearted reimplementation
of a Python list
"""
def __init__(self, data=[1, 2, 3]):
self.data = data
def getitembyindex(self, index=2):
index = min(index, len(self.data))
return self.data[index]