-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18_classes.py
More file actions
59 lines (47 loc) · 1.36 KB
/
18_classes.py
File metadata and controls
59 lines (47 loc) · 1.36 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
58
59
# 1. 인스턴스와 클래스 차이 이해하기
'''
Instance variables are for data which is unique to every object
Class variables are for data shared between different instances of a class
'''
# 2. new style classes
'''
- Old base classes do not inherit from anything
- New style base classes inherit from object
'''
class OldClass():
def __init__(self):
print('I am an old class')
class NewClass(object):
def __init__(self):
print('I am a jazzy new class')
old = OldClass()
# Output: I am an old class
new = NewClass()
# Output: I am a jazzy new class
'''
A major advantage is that you can employ some useful optimizations like __slots__. You can use super() and descriptors and the likes.
'''
# 3. method
# __init__
# __getitem__: Implementing getitem in a class allows its instances to use the [] (indexer) operator.
class GetTest(object):
def __init__(self):
self.info = {
'name':'Yasoob',
'country':'Pakistan',
'number':12345812
}
def __getitem__(self,i):
return self.info[i]
foo = GetTest()
foo['name']
# Output: 'Yasoob'
foo['number']
# Output: 12345812
'''
Without the __getitem__ method we would have got this error:
>>> foo['name']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'GetTest' object has no attribute '__getitem__'
'''