Professional Documents
Culture Documents
Chapter 2
Chapter 2
Output:
<class '__main__.MyClass'>
Code:
p1 = MyClass()
print(p1.x)
Output:
5
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Output:
John
36
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Output:
Hello my name is John
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.16
The self Parameter
The self parameter is a reference to the current instance of the
class, and is used to access variables that belongs to the class.
It does not have to be named self, you can call it whatever you
like, but it has to be the first parameter of any function in the
class:
Example
Code:
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
8/25/2023 8:16 PM Dr. Dipankar Dutta, UIT, BU 1.17
Class and Instance Variables
Instance variables are for data, unique to each instance and
class variables are for attributes and methods shared by all
instances of the class.
Instance variables are variables whose value is assigned inside
a constructor or method with self
whereas class variables are variables whose value is assigned in
the class.
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
print(p1.age)
pass
Output:
Employee created.
Destructor called, Employee deleted.
# Initializing
def __init__(self):
print('Employee created')
# Calling destructor
def __del__(self):
print("Destructor called")
# if datatype is int
# initialize answer as 0
if datatype =='int':
answer = 0
# if datatype is str
# initialize answer as ''
if datatype =='str':
answer ='„”
print(answer)
# Integer
add('int', 5, 6)
# String
add('str', 'Hi ', 'Geeks')
Output:
11
Hi Geeks
Output:
12
17.985999999999997
class MyClass():
def my_method(self, obj):
print('In my_method method of MyClass')
print("Name:", obj.name)
print("Age:", obj.age)
value = add_one(5)
print(value)
Output:
None
def return_greeting():
return "Hello, World“
return_greeting()
'Hello, World„
def describe(sample):
Desc = namedtuple("Desc", ["mean", "median", "mode"])
return Desc(
st.mean(sample),
st.median(sample),
st.mode(sample),
)
stat_desc
Desc(mean=5.7, median=6.0, mode=6)
mean
5.7
mode
6
Questions?