Python
lecture 3
Showcase of Skills and Projects
Presented by: Alexander
Aronowitz
tài liệu ở:
W3school
Date: 27th June 2029
46
Outline
- Function
- Class
- Object
- Constructor
- Public, private, static
47
Function
What is function
A function is a block of code which only runs when it is called.
A function can return data as a result.
A function helps avoiding code repetition.
Advantges of function
Don't Repeat Yourself
Readability
Reusability
Easier Testing and Debugging 48
Function
syntax:
def function_name(parameter): def function_name(parameter):
code code
return value
Ex: Ex:
def my_function(): def my_function(a,b):
print(“hello wolrd”) return a*b
49
Function
Function name
Function names follow the same rules as variable names in Python:
A function name must start with a letter or underscore
A function name can only contain letters, numbers, and
underscores
Function names are case-sensitive (myFunction and myfunction
are different)
50
Function
Arguments & parameter
def function_name(parameter):
code
function_name(argument)
Ex:
def min_1(a,b): #a,b → parameter
if(a<b): return a
else: return b
min_1(3,7) #3,7 → argument 51
Function
Scope
A variable is only available from inside the region it is created. This is
called scope.
x = “Tom” #global scope
local
def myfunc1():
global
x = "Jane" #local scope
nonlocal
def myfunc2():
nonlocal x #nonlocal scope
x = "Kay"
myfunc2()
return x
52
print(myfunc1())
Class
What is class
A class is a blueprint or template for creating objects.
+ attribute
+ method
syntax
class ClassName:
create attributes
def __init__(self, parameters):
pass
def method1(self, parameters): 53
pass
Object
What is object
Object is a concrete entity created from a class.
It represents an instance of the class, containing the data (attributes)
and behavior (methods) that the class defines.
syntax
objetc1 = ClassName()
objetc2 = ClassName(arguments) #if class have constructor
54
Class & Object
Naming Conventions
Class Name: Use PascalCase (e.g. MyClass, StudentAccount).
Method, Variable, Attribute Names: Use snake_case (e.g. my_variable,
calculate_sum, self.student_name).
55
Class & Object
Ex
class Car(): #create a class
pass
car_1 = Car() #create object car1
car_2.brand = ‘Vinfast’ # create an attribute for object car_1
print(car_1.brand)
56
Class & Object
Constructor(__init__ method)
class Car():
def __init__(self,brand,year):
[Link] = brand
[Link] = year
car_1 = Car(“Vinfast”,2018)
print(car_1.brand)
print(car_1.year)
57
Class & Object
Self parameter
class Car():
def __init__(self,brand,year):
[Link] = brand #Instance property
[Link] = year #Instance property
rate = 5 #Class property
car_1 = Car(“Vinfast”,2018)
print(car_1.brand)
print(car_1.year)
del car_1.year
car_1.year = 2020 58
Class & Object
Class method
class Car():
tax = 1.1
def __init__(self,brand,year,price):
[Link] = brand
[Link] = year
[Link] = price
def price_with_tax(self):
print([Link]*[Link])
car_1 = Car('Vinfast', 2018, 10000)
car_1.price_with_tax() 59
Class & Object
__str__ method
class Car():
tax = 1.1
def __init__(self,brand,year,price):
[Link] = brand
[Link] = year
[Link] = price
def __str__(self):
return f"{[Link]} ({[Link]})"
car_1 = Car('Vinfast', 2018, 10000) 60
print(car_1)
Class & Object
Public, private, static
It uses to manage access (who is allowed to see/use it) and
ownership (who it belongs to).
Public/Private answers the question: "Who has access to
this?"
Static answers the question: "Who does this belong to?
(Class or Object?)"
61
Class & Object
Public
A attribute (variable) or method (function) that can be
accessed from anywhere — both inside the class and from
outside the code.
In Python: This is the default. Anything you declare normally
([Link], def my_method(self)) is public.
62
Class & Object
Public
class Car():
tax = 1.1
def __init__(self,brand,year,price):
[Link] = brand #public attribute
[Link] = year #public attribute
[Link] = price #public attribute
def __str__(self): #public method
return f"{[Link]} ({[Link]})"
car_1 = Car('Vinfast', 2018, 10000) 63
print(car_1)
Class & Object
Private
A(n) attribute/method that should only be accessed from
within the class itself.
Purpose: To "hide" implementation details and protect data.
__private (double underscores): This is a Name Mangling
mechanism. Python will automatically rename the variable
self.__balance to _TenClass__balance to make it very difficult
(but not impossible) to access from outside.
64
Class & Object
Private
class Car():
tax = 1.1
def __init__(self,brand,year,licence_plate):
[Link] = brand
[Link] = year
self.__licence_plate = licence_plate #private attribute
def print_licence_plate(self):
print(self.__licence_plate)
car_1 = Car('Vinfast', 2018, ‘F1234’)
print(car_1.licence_plate) #error 65
car_1print_licence_plate()
Class & Object
Static
This is a attribute/method that belongs to the Class, not to a
specific object.
All objects created from that class will share a static
property. You can call it without creating an object.
66
Class & Object
Static attribute
class Car():
tax = 1.1 #static attribute
def __init__(self,brand,year,price):
[Link] = brand #public
[Link] = year #public
[Link] = price #public
car_1 = Car('Vinfast', 2018, 10000)
print(car_1)
67
Class & Object
Static method
class Car():
tax = 1.1 #static attribute
def __init__(self,brand,price):
[Link] = brand #public
[Link] = price #public
@staticmethod
def price_of_2car(x, y): #dont need self method
return x + y
car_1 = Car('Vinfast', 10000)
car_2 = Car(‘BMW’,20000) 68
print(price_of_2car(car_1.price,car_2.price))
Homework function
1. Create a function to check if an entered number is even or
odd, then print the result.
2. Create function that estimates the greatest common multiple
and least common multiple of two numbers a,b.
3. * Write a function to convert integer n in decimal form to
binary form. (recursion)
69
Homework Class & Object
Create a Student class with the following properties: name, age,
score(include math, english, literature,...)
The Student class has an introduce() method to print out the
introduction.
Write a public method called caculate_person_average_score and
static method called calculate_class_average_score that takes in a
list of Student objects and returns the average score.
70