-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14. Classes.py
65 lines (48 loc) · 1.43 KB
/
14. Classes.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
# (self parameter is a reference to the current instance of the class,
# It is used to access variables that belongs to the class
# It does not have to be named self , but should be first)
class MyClass:
# The __init__() Function like Constructor
def __init__(self):
pass
x = "Hi!"
y = lambda self: "This is me"
# Create Object
obj = MyClass()
# Delete Class Properties
del MyClass.x
# -----------------
# Python Inheritance
# Parent Class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# Create a Child Class
class Student(Person):
# When you add the __init__(),
# the child class will no longer inherit the parent's __init__()
# To keep the inheritance of the parent's __init__(),
# add a call to the parent's __init__()
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
# Or Use the super() Function
class Student2(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
# -----------------------GETTER & SETTERS
class Student:
def __init__(self, name):
self._name = name
@property
def name(self):
print('getter method called')
return self._name
@name.setter
def name(self, name):
print('setter method called')
self._name = name
s = Student('asad')
s.name = 'Ali'