0% found this document useful (0 votes)
2 views

07_Class_I _Basics-2

Uploaded by

haeinpark1376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

07_Class_I _Basics-2

Uploaded by

haeinpark1376
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lecture 07

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

• We've learned several types.


– int, float, bool, str
– list, tuple, set, dictionary
– We call the above Python-providing types the built-in classes.
• Often we want to define our own data types
– such as vectors, matrices, images, and so on…
• Can we define our own types in Python?
– Yes, we can!
– That is what the class is for.
Class and Object

Class defines what the object should be.


Each instance of the class is called an object.
Object is also called as an instance.
Class and Object

class Person :
name = "Default Name"
year_born = 1996 Class definition
def Print(self):
print("I am", self.name, 2024 - self.year_born, "years old.")

p1 = Person() 1st object creation


p1.name = "Steve"; p1.year_born = 2000
p1.Print()

p2 = Person() 2nd object creation


p2.name = "In-Soo"; p2.year_born = 1983
p2.Print()

I am Steve 24 years old.


I am In-Soo 41 years old.
A Class Consists of…

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.

The following produces the same result as above.


class Person :
name = "Default Name "
def Print(abc):
print("I am", abc.name)

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 Result


class Person: p = Person('Kim', 23) True
species = 'Homo Sapiens' True
# instance attributes True
def __init__(self, name, age): print(hasattr(p, 'species')) True
self.name = name print(hasattr(p, 'name')) True
self.age = age print(hasattr(p, 'age')) True
print(hasattr(p, '__init__'))
def printName(self): print(hasattr(p, 'printName')) True
print('Name: ', self.name) print(hasattr(p, 'printAge’)) False
False
def printAge(self): # class attributes – not taught yet True
print('Age: ', self.age) # Just run and see the results... True
print(hasattr(Person, 'species')) True
print(hasattr(Person, 'name'))
print(hasattr(Person, 'age'))
print(hasattr(Person, '__init__'))
print(hasattr(Person, 'printName'))
print(hasattr(Person, 'printAge'), '\n')
Differentiating the class attributes vs. instance
attributes can be confusing to learn at the
beginning.
Type&Run: getattr(object, name[, default])
#1. Variables

Source code Result


class Person: p = Person('Kim', 23) Homo Sapiens
species = 'Homo Sapiens' Kim
print(p.species) 23
def __init__(self, name, age): print(p.name) Homo Sapiens
self.name = name print(p.age) Kim
self.age = age 23
print(getattr(p, 'species')) None
def printName(self): print(getattr(p, 'name')) Homo Sapiens
print('Name: ', self.name) print(getattr(p, 'age')) Homo Sapiens
#print(getattr(p, 'job')) None
def printAge(self): print(getattr(p, 'job', None))
print('Age: ', self.age)
print(Person.species)
#print(Person.name)
print(getattr(Person, 'species'))
#print(getattr(Person, 'name'))
print(getattr(Person, 'name', None), '\n')

Commented lines produce errors


Type&Run: getattr(object, name[, default])
#2. Functions

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

Source code Result


class Person: p = Person('Kim', 23) Name: Kim
species = 'Homo Sapiens' Age: 23
p.func1('printName') Name: Kim
def __init__(self, name, age): p.func1('printAge') Age: 23
self.name = name p.func2('printName')
self.age = age p.func2('printAge')

def printName(self):
print('Name: ', self.name)

def printAge(self):
print('Age: ', self.age)

def func1(self, attr):


if attr == 'printName':
self.printName()
elif attr == 'printAge':
self.printAge()

def func2(self, attr):


getattr(self, attr)()
Type&Run: setattr(object, name, value)
#1. Variables

Source code Result


class Person: p = Person('Kim', 23) Homo Sapiens
species = 'Homo Sapiens' 2
Person.leg = 2 2
def __init__(self, name, age): p.job = 'student'
self.name = name Kim
self.age = age setattr(Person, 'arm', 2) 23
setattr(p, 'nation', 'Korea') student
def printName(self): Korea
print('Name: ', self.name) print(Person.species)
print(Person.leg)
def printAge(self): print(Person.arm, '\n')
print('Age: ', self.age)
print(p.name)
print(p.age)
print(p.job)
print(p.nation)
Type&Run: setattr(object, name, value)
#2. Functions

Source code
class Person: def printNameFunc(self):
species = 'Homo Sapiens' print('Name: ', self.name)

def __init__(self, name, age): def printAgeFunc(self):


self.name = name print('Age: ', self.age)
self.age = age
p = Person('Kim', 23)

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')

def printName(self): #print(Person.species)


print('Name: ', self.name) #print(Person.leg)
#print(p.name)
def printAge(self): #print(p.age)
print('Age: ', self.age)
Commented lines produce errors
Type&Run: del statement (class object)

Source code Result


class X: <__main__.X object at 0x0000024453A8D8D0>
type = 'abc' abc 0 A
def __init__(self, id, name): X class
self.id = id
self.name = name
def Print(self):
print('X class')

obj = X(0, 'A')

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

The strings in the tuple are


replaced to each %s. A tuple comes after %

print("Hello %s, my name is %s" % ('john', 'mike'))


print("My name is %s and i'm %d" % ('john', 12))
If an integer is to come, use %d instead.
Hello john, my name is mike
My name is john and i'm 12

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 Result


s = 'string: %d' % 123 string: 123
print(s) string: 0.666667
s = 'string: %f' % (2/3) # (2/3)
string: 123 123.120000 345.670000
print(s)
s = 'string: %i %f %f' % (123.12, 123.12, 345.67) string: 123.46 345.679
print(s) string: 1.234560e+02, 3.456789E+02
s = 'string: %10.2f %.3f' % (123.4567, 345.6789) string: 1.23000e+00, 3.450E+01
print(s) string: abc
s = 'string: %e, %E' % (123.456, 345.6789) string: a
print(s)
s = 'string: %.5e, %15.3E' % (1.23, 34.5)
print(s)
s = 'string: %s' % 'abc'
print(s)
s = 'string: %c' % 'a'
print(s)
Type&Run: The Format Function

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

You might also like