-
Notifications
You must be signed in to change notification settings - Fork 44
/
Chapter_9th_class.py
122 lines (88 loc) · 1.84 KB
/
Chapter_9th_class.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
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
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 13:15:35 2020
@author: sana.rasheed
"""
### Chapter 9th - Class
# Example 1
class MyClass:
x = 5
print(MyClass)
# Output
# <class '__main__.MyClass'>
# Example 2
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
# Output
# 5
# Example 3
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
# Output
# John
# 36
# Example 4
class Person:
def __init__(myobject, name, age):
myobject.name = name
myobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
# Output
# Hello my name is John
# Example 5
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
# Output
# Hello my name is John
# Example 6
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
# Output
# 40
# Example 7
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1.age # delete p1.age
print(p1.age) # return an error as p1.age is deleted
# Output
# AttributeError: 'Person' object has no attribute 'age'
# Example 8
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
del p1 # delete p1
print(p1) # return an error as p1 is deleted
# Output
# NameError: name 'p1' is not defined