object-oriented programming in python - webzdarma · object-oriented programming in python . class...
TRANSCRIPT
Jan Hnilica Computer modelling 7 1
Object-oriented programming in Python
Class – basic definitions
2 Jan Hnilica Computer modelling 7
I. a class represents any object (either from the real world or something abstract)
II. a class groups together 1. data (describing the qualities/properties of the object) 2. functions (defining the abilities of the object)
(such an integration into a compact entity is called encapsulation)
III. a class constitutes a new data type
IV. a variable of this data type is called object
Data and functions
3 Jan Hnilica Computer modelling 7
Data (data members) • specific for each object • usually they are private = directly accessible only for objects of a given class • access to the data is usually provided through the functions of the class
Functions (methods) • common for all objects of a given class • usually they are public = called by external parts of a program • part of them manages the data (access methods)
Declaration of a class
4 Jan Hnilica Computer modelling 7
• in general:
class name: block of declarations
• the first line consists of: 1. the reserved word class
2. a name of the class 3. a colon
• the block of declarations • contains the declarations of particular methods • all declarations in the block are equally indented
Simple example
5 Jan Hnilica Computer modelling 7
• the declaration of the class Square
class Square: # public data member (and its initial value) edge = 1 # methods def area(self): return self.edge * self.edge def perimeter(self): return 4 * seld.edge
• the class contains: • one data member: edge
• two methods: area() and perimeter()
Parameter self
6 Jan Hnilica Computer modelling 7
• each Python method takes at least one argument, usually named self
def area(self): return self.edge * self.edge def perimeter(self): return 4 * seld.edge
Parameter self • required in all Python methods • does not need to be named self, but it is a common practice • contains the reference to the object, which actually uses the method • data members are accessible through the self parameter: self.member • the parameter self is not written, when a method is called (see later)
Working with objects
7 Jan Hnilica Computer modelling 7
# a new variable of the data type Square s = Square()
• data members and methods are accessible through an object of given class • syntax:
# setting a new value to the data member edge s.edge = 10 # call of the method area() a = s.area() # the parameter self is omitted print(“area is”, a)
• creation of an object
object.data_member object.method(...)
Public and private data members
8 Jan Hnilica Computer modelling 7
s = Square() s.edge = -5 # negative edge!
• public data members are accessible from any part of the program • they can be changed in an improper way
• the common practice is that the data members should be private
Public data members • directly accessible from outer parts of a program
Private data members • hidden from the outside • directly accessible only for the objects of given class • a class usually provides special methods for manipulation with private
data members (access methods)
Public and private data members
9 Jan Hnilica Computer modelling 7
• a simple rule: name of a private data member starts with two underscores
# public data member member = value # private data member __member = value
• private data members are hiden from the outside, therefore the class usually provides public methods for manipulation with them – access methods
Assess methods
10 Jan Hnilica Computer modelling 7
• allow to manage private data members • usually there is a couple of access methods for each private data member:
1. get_member • returns the actual value of data members • usually has no parameters (except the self, which is obligatory)
2. set_member • sets a new value of the data member • usually has one parameter: a new value
Class with private data member
11 Jan Hnilica Computer modelling 7
class Square: # private data member (initial values) __edge = 1 # access methods def get_edge(self): return self.__edge; def set_edge(self, value): if value > 0: # protection against negative values self.__edge = value # other methods def area(self): return self.__edge * self.__edge def perimeter(self): return 4 * self.__edge;
Other methods
12 Jan Hnilica Computer modelling 7
# the method draws the rectangle to the screen def draw(self, symbol = "x"): for i in range(self.__edge): print(symbol * self.__edge) # in program s = Square() s.set_edge(4) # using the default symbol s.draw() # using a given symbol s.draw("*")
• methods access the data through the self parameter • can take other parameters (both positional and keyword)
xxxx xxxx xxxx xxxx ****
**** **** ****
Constructor
13 Jan Hnilica Computer modelling 7
• a method creating a particular object of the class • in Python, the constructor is the method named __init__ • usually the declaration and initialization of data members is done within
the body of constructor
def __init__(self): self.__edge = 1 # initializing data member
two underscores before and behind the name
• the constructor (the __init__ method) is called, whenever an object of the class is created
s = Square() # call of the constructor
More about constructors
14 Jan Hnilica Computer modelling 7
Default constructor • when we do not declare a constructor, Python itself supplies the default
constructor for our class • therefore we are still able to create an object even without the __init__ method
(Python use its default constructor) • the default constructor supplied by Python does not initialize the data members!
class Greeting: # member function def greet(self): print("Hello!!!") # in program g = Greeting() # using the default constructor g.greet()
More about constructors
15 Jan Hnilica Computer modelling 7
Parametrized constructor • = constructor with parameters (arguments)
# the constructor with a positional parameter def __init__(self, value): self.__edge = value # in program s = Square(5) # creating the object with a given edge s.draw() xxxxx
xxxxx xxxxx xxxxx xxxxx
More about constructors
16 Jan Hnilica Computer modelling 7
Parametrized constructor • a constructor can take keyword parameters as well
# the constructor with a keyword parameter def __init__(self, value = 3): self.__edge = value # in program s1 = Square() # default value s1.draw() s2 = Square(5) # given value s2.draw()
xxx xxx xxx
xxxxx xxxxx xxxxx xxxxx xxxxx
__str__ method
17 Jan Hnilica Computer modelling 7
• returns a text representation of an object • the __str__ method is called when the object is printed to the screen
through the built-in print function • any class can implement its __str__ method, which allows to print its objects
using the syntax print(object)
# implementation of __str__ method def __str__(self): return "square with the edge = {}".format(self.__edge) # in program s = Square(5) print(s) square with the edge = 5
Note: __str__ is one of the magic methods, which allow to customize your class.
Passing objects to a function
18 Jan Hnilica Computer modelling 7
• objects are passed by reference ⇒ the function treats the original object, not its copy ⇒ changes of the object appear outside the function
# function working with an object def func(sqr): sqr.set_edge(4) # in program s = Square(2) s.draw() func(s) s.draw()
xx xx
xxxx xxxx xxxx xxxx
Copying the objects
19 Jan Hnilica Computer modelling 7
• a simple assignment does not work, as it only creates another reference to the existing variable
s1 = Square(2) s2 = s1 # s2 is only a new reference s1.set_edge(3) print(s1) print(s2)
square with the edge = 3 square with the edge = 3 output:
s1
s2 object
Copying the objects
20 Jan Hnilica Computer modelling 7
• a true copy can be made using the functions from the module copy
# import of the module import copy s1 = Square(2) s2 = copy.copy(s1) s1.set_edge(3) print(s1) print(s2)
square with the edge = 3 square with the edge = 2 output:
s1
s2
object
copy of the object
call of a function from a module: modul_name.function_name()
Shallow versus deep copy
21 Jan Hnilica Computer modelling 7
• the function copy makes the exact copies of all data members = shallow copy • a shallow copy suffices when the data members are of fundamental data types,
however a problem arises when data members are references
x
y
object
copy of the object
data member
• in such case the function deepcopy is necessary:
y = copy.deepcopy(x)
y = copy.copy(x)
x
y
object
copy of the object
data member
copy of the data member
Docstrings
22 Jan Hnilica Computer modelling 7
• docstring = documentation string (comment) • starts and finishes with triple quotes (single or double) • is placed as the first statement in the class declaration
• usage: docstring is generated by the inbuild function help(...)
class MyClass: """ docstring is a place for important information about the class, method, function, module... """ ... # in program help(MyClass) # prints the text of docstring
Jan Hnilica Computer modelling 7 23
• usage of the self parameter... def test(self, x): if (id(self) == id(x)): print("my parameter is me!!!") s = Square() s.test(s)
• adding new members to an existing object...
• checking the type of the object...
s = Square() s.new_member = "hello" print(s.new_member)
s = Square() if (type(s) == Square): ... if (isinstance(s, Square)): ...