07_Class_I _Basics-2
07_Class_I _Basics-2
Class I – Basics
Prof. Hyeong-Seok Ko
Seoul National University
Dept. of Electrical and Computer Engineering
Contents
• Classes and Objects
• self Variable
• Constructor
• Destructor
• Built-In Functions for Classes/Objects
• String Formatting
What is Class?
It is a Custom Type
class Person :
name = "Default Name"
year_born = 1996 Class definition
def Print(self):
print("I am", self.name, 2024 - self.year_born, "years old.")
class Person :
name = "Default Name "
year_born = 1996
def Print(self):
print("I am", self.name, 2024 - self.year_born, "years old.")
• Member Variables
– Variables used for defining the class
– e.g., name, year_born = attributes = properties
• Member Functions = Member Methods
– Functions that are defined in the class
– e.g., Print()
self Variable
class Person :
name = "Default Name "
def Print(self): • Every member function has self as the first parameter.
print("I am", self.name) • self refers to the current object
• In this call, p1 is passed to self.
p1 = Person()
p1.name = "Steve"
• The name does not have to be self.
p1.Print() • The first one among the parameters takes that role.
p1 = Person()
p1.name = "Steve"
p1.Print()
self Variable
class Person :
name = "Default Name "
def Print(self): • Every member function has self as the first parameter.
print("I am", self.name) • self refers to the current object
• In this call, p1 is passed to self.
p1 = Person()
p1.name = "Steve"
• The name does not have to be self.
p1.Print() • The first one among the parameters takes that role.
The member function can have additional parameters than self.
class Person :
givenName = "Default Given Name "
familyName = "Default Family Name "
def Print(self, GivenOrFamilyName):
if(GivenOrFamilyName == 'G'): My given name is Steve
print("My given name is", self.givenName) My family name is Ko
else:
print("My family name is", self.familyName)
p1 = Person()
p1.givenName = "Steve"; p1.familyName = "Ko"
p1.Print('G')
p1.Print('F')
Constructor
• A special method __init__, which is automatically called whenever we create an
object of that class, is called the constructor.
– You can put any statements in the constructor.
– However, usually you program the constructor to ensure that the data members of each
object start out with sensible initial values.
class Person :
def __init__(self, name):
self.name = name
def Print(self):
My name is Steve
print("My name is", self.name)
My name is In-Soo
p1 = Person("Steve")
p2 = Person("In-Soo")
p1.Print()
p2.Print()
Destructor
• A special method __del__, which is automatically called when an object goes out of scope
or when a dynamically allocated object is deleted, is called the destructor.
class Person :
def __init__(self, *args):
if len(args) == 0 :
self.name = "Default"
elif len(args) == 1 :
x = args[0]
self.name = x
My name is Default
def __del__(self): My name is Steve
print("Destructor called") Destructor called
Destructor called
def Print(self):
print("My name is", self.name)
def func():
p1 = Person(); p1.Print();
p2 = Person("Steve"); p2.Print();
func()
Constructor with Varying # of Arguments
class Person :
def __init__(self, *args): • Python can have only one constructor.
if len(args) == 0 : • You can make the constructor take varying number
self.name = "Default" of arguments using *args.
elif len(args) == 1 : • In the call p1 = Person(), args = (), an empty
self.name = args[0] tuple.
• In the call p2 = Person("Steve"), args =
def Print(self): ("Steve"), a tuple having one element.
print("My name is", self.name) • args is the tuple Python automatically provides to
the called function.
p1 = Person(); p1.Print() • * is the key notation, but args is not.
p2 = Person("Steve"); p2.Print() • You could have used *abc instead.
My name is Default
My name is Steve
Class Exercise: Constructor with Varying # of Arguments
class Vector3 :
def __init__(self, *args):
# program this part yourself...
[ -1 0 0 ]
[ 1 2 3 ]
def Print(self): [ 0 0 0 ]
print("[", self.x, self.y, self.z, "]")
v0 = Vector3(-1,0,0)
v1 = Vector3(1,2,3)
v2 = Vector3()
v0.Print()
v1.Print()
v2.Print()
Built-in Functions for Class/Object
(hasattr, getattr, setattr, delattr)
Type&Run: hasattr(object, name)
Source code
class Person: p = Person('Kim', 23)
species = 'Homo Sapiens'
print(p.printName)
def __init__(self, name, age): print(getattr(p, 'printName'))
self.name = name
self.age = age p.printName()
p.printAge()
def printName(self): getattr(p, 'printName')() applies this func to self
print('Name: ', self.name) getattr(p, 'printAge')()
def printAge(self):
print('Age: ', self.age)
Result
<bound method Person.printName of <__main__.Person object at 0x000001896CE8D340>>
<bound method Person.printName of <__main__.Person object at 0x000001896CE8D340>>
Name: Kim
Age: 23
Name: Kim
Age: 23
Type&Run: getattr(object, name[, default])
#3. etc
def printName(self):
print('Name: ', self.name)
def printAge(self):
print('Age: ', self.age)
Source code
class Person: def printNameFunc(self):
species = 'Homo Sapiens' print('Name: ', self.name)
Person.printName = printNameFunc
setattr(Person, 'printAge', printAgeFunc)
p.printName()
p.printAge()
Result
Name: Kim
Age: 23
Type&Run: delattr(object, name)
Source code
class Person: p = Person('Kim', 23)
species = 'Homo Sapiens'
leg = 2 del Person.species
del p.name
def __init__(self, name, age):
self.name = name delattr(Person, 'leg')
self.age = age delattr(p, 'age')
print(obj)
print(obj.type, obj.id, obj.name)
obj.Print()
#del obj.type # error, it is class var
del obj.id
#print(obj.id) # error
del obj
#print(obj) # error
String Formatting
Introduction to String Formatting
def makeString(L):
toReturn = ''
for i in range(0, len(L)):
toReturn += "%.2f" % L[i] 1.00 2.00 3.00
if i != len(L): For a float, use %f. instead of %s or %d.
toReturn += ' '
return toReturn See how digits after decimal point is specified.
L1 = [1, 2, 3]
print(makeString(L1))
Type&Run: % Operator
Source code
s = 'Name: {}'.format('Ko')
print(s)
s = 'Name: {} / ID: {}'.format('Kim', '2021-11111')
print(s)
s = 'Name: {0} / ID: {2} / Age: {1}'.format('Lee', 20, '2021-22222')
print(s)
s = 'Name: {name} / ID: {id} / Age: {age}'.format(age = 21, id = '2021-33333', name = 'Shin')
print(s)
s = 'Name: {name} / ID: {id} / Age: {age}'
print(s.format(age = 22, id = '2021-44444', name = 'Jang'))
Result
Name: Ko
Name: Kim / ID: 2021-11111
Name: Lee / ID: 2021-22222 / Age: 20
Name: Shin / ID: 2021-33333 / Age: 21
Name: Jang / ID: 2021-44444 / Age: 22
Type&Run: f-String Formatting
Source code
name = 'Ko'
s = 'coffee'
s = f'Name: {name}'
n = 5
print(s)
str = f'저는 {s}를 좋아합니다. 하루 {n}잔 마셔요.'
print(str)
num = 1.23
s = f'Number: {num:.3f}'
저는 coffee를 좋아합니다. 하루 5잔 마셔요.
print(s)
a = 1
b = 2
s = f'Sum: {a+b}'
• f-string formatting was more recently introduced than print(s)
the % operator and format function.
Result
• f'문자열 {변수} 문자열' 의 꼴임
Name: Ko
• 문자열 맨 앞에 f를 붙여주고, 중괄호 안에 직접 변수 Number: 1.230
이름이나 출력하고 싶은 것을 바로 넣으면 됨. Sum: 3
Lecture 07
Class I - Basics
The End