-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpythonclassdefinition.txt
128 lines (92 loc) · 2.58 KB
/
pythonclassdefinition.txt
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#CLASSES
#constructor declaration
def __init__(self):
# body of the constructor
#self constructors - definition & declaration
class GeekforGeeks:
geek = ""
# default constructor
def __init__(self):
self.geek = "GeekforGeeks"
# a method for printing data members
def print_Geek(self):
print(self.geek)
# creating object of the class
obj = GeekforGeeks()
# calling the instance method using the object obj
obj.print_Geek()
#Parameterized Constructors
##PARAMETER PASSING
lass Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
# creating object of the class
# this will invoke parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
obj.calculate()
# display result
obj.display()
#CLASS
class Shark:
def swim(self):
print("The shark is swimming.")
def be_awesome(self):
print("The shark is being awesome.")
def main():
sammy = Shark()
sammy.swim()
sammy.be_awesome()
if __name__ == "__main__":
main()
#Definition1
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
# Reference the name
print(self.name + " is swimming.")
def be_awesome(self):
# Reference the name
print(self.name + " is being awesome.")
#Definition2 - positional argument
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
print(self.name + " is swimming.")
def be_awesome(self):
print(self.name + " is being awesome.")
def main():
# Set name of Shark object
sammy = Shark("Sammy")
sammy.swim()
sammy.be_awesome()
if __name__ == "__main__":
main()
#Definition3 - class instantiation
class Shark:
def __init__(self, name):
self.name = name
def swim(self):
print(self.name + " is swimming.")
def be_awesome(self):
print(self.name + " is being awesome.")
def main():
sammy = Shark("Sammy")
sammy.be_awesome()
stevie = Shark("Stevie")
stevie.swim()
if __name__ == "__main__":
main()