4. Model: A
Color: orange
Price: 10k
Objects
Class: Car
Model: B
Color: blue
Price: 25k
Car
Model:
Color:
Price:
Drive
Park
Start
Stop
State
Behaviors
Methods(a.k.a
functions)
Attributes
(a.k.a variables)
5. The class is a user-defined data structure that binds the
data members and methods into a single unit. Class is
a blueprint or code template for object creation. Using a
class, you can create as many objects as you want.
An object is an instance of a class. It is a collection of
attributes (variables) and methods. We use the object of
a class to perform actions.
Define
a class
6. Classes have methods and attributes
In Python, creating a method defines a class behavior. The word method is the OOP name given to a
function that is defined within a class. To sum up:
• Class functions is synonym for methods
• Class variables is synonym for name attributes
• Type – indicates the class the instance belongs to
• Attribute – Any object value: object.attribute
• Method – a “callable attribute” defined in the class
8. The following code shows how to create our first class and
then its instance.
class Car:
def __init__(self, model, color, price, fuel_type):
# data members (instance variables)
self.model = model
self.color = color
self.price = price
self.fuel_type = fuel_type
# Behavior (instance methods)
def show(self):
print(‘Model:', self.model, ‘Color:', self.color, ‘Price:', self.price)
# Behavior (instance methods)
def get_fuel_type(self):
print(self.model, ‘run on a', self.fuel_type)
# create object of a class
a = Car(‘A', ‘orange', ‘10k’, ‘Gasoline’)
# call methods
a.show()
a. get_fuel_type()
9. Use class to
define classes
Python uses class to create objects.
Every defined class has a special
method called __init__(), which allows
you to control how objects are initialized.
Methods within your class are defined in
much the same way as functions, that
is, using def. Here’s the basic form:
10. 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 (keyword is
equivalent to “this” in C#/Java).
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:
11. The importance of self
This is a very important argument assignment.
Without it, the Python interpreter can’t work out which object instance to apply
the method invocation to.
Note that the class code is designed to be shared among all of the object
instances: the methods are shared, the attributes are not. The self argument
helps identify which object instance’s data to work on.
12. References:
• Python Object-Oriented Programming (OOP) – Pynative
• Python Classes (w3schools.com)
• Head First Python (bedford-computing.co.uk)
• https://realpython.com/lessons/classes-python/
• https://www.youtube.com/watch?v=8yjkWGRlUmY&t=0s
• Изучаем программирование на Python ( PDFDrive ).pdf