-
Notifications
You must be signed in to change notification settings - Fork 0
/
dunderMethods.py
95 lines (63 loc) · 2.04 KB
/
dunderMethods.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Movie:
def __init__(self, name, release_year):
self.name = name
self.release_year = release_year
def __str__(self) :
return self.name
def __lt__(self, other_object):
return self.release_year < other_object.release_year
def __call__(self) :
return "say hello to my dear friend ! "
movie = Movie('122 angry man' , 1997)
# checking Dunder(magic) methods
# __str__ :
#when we call print the __str__ method will call
# print(movie.__str__)
# print(str(movie))
# print(movie)
# __it__ :
hungergame = Movie('hungergame' , 2009)
se7en = Movie('se7en' , 1995)
print(se7en.__lt__(hungergame))
print(se7en > hungergame)
# we have some other methods for operator overloading
# __lt__ for : a < b
# __gt__ for : a > b
# __le__ for : a <= b
# __ge__ for : a >= b
# __eq__ for : a == b
# __ne__ for : a != b
scarface = Movie('scarface' , 2013)
#scarface()
# we will have :
# TypeError: 'Movie' object is not callable
# how to make it callable ? :
# __cal__ :
#after adding __cal__ :
print(scarface())
print(scarface.__call__())
# lets go for more usable Dunder methods :
class FootballTeam:
def __init__(self, name, cups_number):
self.name = name
self.cups_number = cups_number
def __add__(self, other_object):
return self.cups_number + other_object.cups_number
ss = FootballTeam('Esteghlal' , 20)
loung = FootballTeam('pirouzi' , 17)
print(ss + loung)
print(ss.__add__(loung))
# a + b __add__
# تفریق a - b __sub__
# ضرب a * b __mul__
# تقسیم اعشاری a / b __truediv__
# تقسیم صحیح a // b __floordiv__
# باقیمانده a % b __mod__
# توان a ** b __pow__
# شیفت چپ a << b __lshift__
# شیفت راست a >> b __rshift__
# AND a & b __and__
# OR a ا b __or__
# XOR a ^ b __xor__
# NOT ~a __invert__
# another one : __len__ , __iter__ , __next__