Объектно-ориентированное программирование
Содержание:
Tutorial Series
Object-Oriented Programming in Python 3
Object-oriented programming (OOP) focuses on creating reusable patterns of code, in contrast to procedural programming, which focuses on explicit sequenced instructions. When working on complex programs in particular, object-oriented programming lets you reuse code and write code that is more readable, which in turn makes it more maintainable.
Next in series: How To Use the Python Debugger
How To Code in Python 3
Python is an extremely readable and versatile programming language. Written in a relatively straightforward style with immediate feedback on errors, Python offers simplicity and versatility, in terms of extensibility and supported paradigms.
Next in series: How To Use the Python Debugger
Deleting Attributes and Objects
Any attribute of an object can be deleted anytime, using the statement. Try the following on the Python shell to see the output.
We can even delete the object itself, using the del statement.
Actually, it is more complicated than that. When we do , a new instance object is created in memory and the name c1 binds with it.
On the command , this binding is removed and the name c1 is deleted from the corresponding namespace. The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed.
This automatic destruction of unreferenced objects in Python is also called garbage collection.
Deleting objects in Python removes the name binding
Множественное наследование
Множественное наследование подразумевает, что класс может наследовать атрибуты и методы из нескольких родительских классов одновременно. Это позволяет программам сократить избыточность, но также может усложнить код, поэтому множественное наследование нужно использовать только с учетом общей конструкции программы.
Попробуйте создать класс Coral_reef, дочерний по отношению к классам Coral и Sea_anemone. Создайте в каждом классе метод и передайте его с помощью ключевого слова pass в дочерний класс Coral_reef.
Класс Coral содержит метод community(), который выводит одну строку текста, а класс Anemone содержит метод protect_clownfish(), который отображает другую строку. После этого оба класса вызываются в кортеж. Таким образом класс Coral может наследовать оба родительских класса.
Создайте объект класса Coral:
Объект great_barrier класса CoralReef использует методы обоих родительских классов.
Запустите код:
Как видите, множественное наследование работает правильно.
Множественное наследование позволяет использовать методы нескольких родительских классов внутри одного дочернего класса. Если в родительских классах присутствует один и тот же метод, дочерний класс унаследует его из того родительского класса, который идёт первым в кортеже.
Data Hiding
An object’s attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.
Example
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
When the above code is executed, it produces the following result −
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −
......................... print counter._JustCounter__secretCount
When the above code is executed, it produces the following result −
1 2 2
Previous Page
Print Page
Next Page
Built-In Class Attributes
Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −
-
__dict__ − Dictionary containing the class’s namespace.
-
__doc__ − Class documentation string or none, if undefined.
-
__name__ − Class name.
-
__module__ − Module name in which the class is defined. This attribute is «__main__» in interactive mode.
-
__bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
For the above class let us try to access all these attributes −
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__
When the above code is executed, it produces the following result −
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
Полиморфизм в методах классов
Чтобы посмотреть, как Python использует каждый из этих классов, создайте цикл for, который итерирует корсаж объектов. Затем можно вызвать методы, не указывая, к какому классу относится каждый из них. Достаточно просто указать, что такой метод существует.
Теперь у вас есть два объекта, wally из класса Shark и casey из класса Clownfish. Цикл for итерирует методы swim(), swim_backwards() и skeleton() каждого объекта.
Запустите программу. Она выведет:
Цикл for сначала итерировал объект класса Shark, а затем объект класса Clownfish.
Как видите, Python использует эти методы, не зная точно, к какому классу относится каждый из них.
Что такое полиморфизм?
Полиморфизм – важная функция в определении классов Python. Она применяется тогда, когда у классов или подклассов есть общие методы. Таким образом, функции могут использовать объекты любого из этих полиморфных классов, не зная различий между классами.
Полиморфизм в Python основан на утиной типизации. Термин «утиная типизация» (также неявная типизация, или латентная типизация) произошёл от цитаты «Если это выглядит как утка, плавает как утка и крякает как утка, то это, возможно, и есть утка». Утиная типизация подразумевает определение пригодности объекта для конкретной цели. При использовании обычной типизации эта пригодность определяется типом объекта в отдельности, но в утиной типизации для этого используются методы и свойства рассматриваемого объекта. Иными словами, нужно проверить, крякает ли объект как утка, а не спрашивать, является ли объект уткой.
Если несколько классов содержат методы с одинаковыми именами, но реализуют их по-разному, эти классы являются полиморфными. Функция сможет оценить эти полиморфные методы, не зная, какой класс она вызывает.
Define Polymorphism?
The word polymorphism is composed of two words ‘poly’ and ‘morphs’. The word ‘poly’ means many and ‘morphs’ means forms. In short, polymorphism means having many forms.
A real-life example of polymorphism is any person who’s having many different characteristics. Like an employee at office, a husband and a father at home will have different behaviour everywhere.
Polymorphism helps us in performing many different operations using a single entity. A basic example of polymorphism is a ‘+’ operator. We know we can add as well as concatenate numbers and string respectively. With the help of ‘+’ operator.
Подклассы
Настоящая сила классов становится очевидной, когда вопрос касается подклассов. Вы, возможно, еще не поняли это, но мы уже создали подкласс, когда создавали класс, основанный на объекте. Другими словами, «подклассифицировали» объект. Так как объект – это не очень интересная тема, предыдущие примеры не уделили должного внимания такому сильному инструменту как подкласс. Давайте подклассифицируем наш класс Vehicle и узнаем, как все это работает.
Python
class Car(Vehicle):
«»»
The Car class
«»»
#———————————————————————-
def brake(self):
«»»
Override brake method
«»»
return «The car class is breaking slowly!»
if __name__ == «__main__»:
car = Car(«yellow», 2, 4, «car»)
car.brake()
‘The car class is breaking slowly!’
car.drive()
«I’m driving a yellow car!»
|
1 |
classCar(Vehicle) «»» The Car class #———————————————————————- defbrake(self) «»» Override brake method return»The car class is breaking slowly!» if__name__==»__main__» car=Car(«yellow»,2,4,»car») car.brake() ‘The car class is breaking slowly!’ car.drive() «I’m driving a yellow car!» |
В этом примере, мы подклассифицировали класс Vehicle. Вы могли заметить, что мы не использовали методы __init__ и drive. Причина в том, что когда мы хотим сделать из класса подкласс, мы уже имеем все атрибуты и методы, только если мы не переопределяем их. Таким образом, вы могли заметить, что мы переопределяем метод brake и указываем ему делать кое-что другое. Другие методы остаются такими же, какими они и были до этого. Так что, когда вы указываете автомобилю тормозить, он использует оригинальный метод, и мы узнали, что мы водим желтый автомобиль. Когда мы используем значения родительского класса по умолчанию – мы называем это наследование.
Это достаточно большой раздел в объектно-ориентированном программировании. Это также простой пример полиморфизма. Полиморфические классы имеют одинаковый интерфейс (методы, атрибуты), но они не контактируют друг с другом. Касаемо полиморфизма в Пайтоне, не очень сложно выяснить, что интерфейсы являются идентичными. С этого момента мы знакомимся с понятием утиная типизация. Суть утиной типизации заключается в том, что если это ходит как утка, и крякает как утка – значит, это должна быть утка.
В Пайтоне, если класс содержит методы, которые называются одинаково, то не имеет значения, если реализация этих методов отлична. В любом случае, вам пока не нужно знать все подробности использования классов в Пайтоне. Вам нужно только хорошо разбираться в терминологии, если вы захотите углубиться в вопрос глубже. Вы можете найти много хороших примеров полиморфизма в Python, которые помогут вам понять, как и зачем вы можете использовать этот концепт в собственных приложениях.
Logging
The logging module has been a part of Python’s Standard Library since Python version 2.3. As it’s a built-in module all Python module can participate in logging, so that our application log can include your own message integrated with messages from third party module. It provides a lot of flexibility and functionality.
Benefits of Logging
-
Diagnostic logging − It records events related to the application’s operation.
-
Audit logging − It records events for business analysis.
Messages are written and logged at levels of “severity” &minu
-
DEBUG (debug()) − diagnostic messages for development.
-
INFO (info()) − standard “progress” messages.
-
WARNING (warning()) − detected a non-serious issue.
-
ERROR (error()) − encountered an error, possibly serious.
-
CRITICAL (critical()) − usually a fatal error (program stops).
Let’s looks into below simple program,
import logging
logging.basicConfig(level=logging.INFO)
logging.debug('this message will be ignored') # This will not print
logging.info('This should be logged') # it'll print
logging.warning('And this, too') # It'll print
Above we are logging messages on severity level. First we import the module, call basicConfig and set the logging level. Level we set above is INFO. Then we have three different statement: debug statement, info statement and a warning statement.
Output of logging1.py
INFO:root:This should be logged WARNING:root:And this, too
As the info statement is below debug statement, we are not able to see the debug message. To get the debug statement too in the Output terminal, all we need to change is the basicConfig level.
logging.basicConfig(level = logging.DEBUG)
And in the Output we can see,
DEBUG:root:this message will be ignored INFO:root:This should be logged WARNING:root:And this, too
Also the default behavior means if we don’t set any logging level is warning. Just comment out the second line from the above program and run the code.
#logging.basicConfig(level = logging.DEBUG)
Output
WARNING:root:And this, too
Python built in logging level are actually integers.
>>> import logging >>> >>> logging.DEBUG 10 >>> logging.CRITICAL 50 >>> logging.WARNING 30 >>> logging.INFO 20 >>> logging.ERROR 40 >>>
We can also save the log messages into the file.
logging.basicConfig(level = logging.DEBUG, filename = 'logging.log')
Now all log messages will go the file (logging.log) in your current working directory instead of the screen. This is a much better approach as it lets us to do post analysis of the messages we got.
We can also set the date stamp with our log message.
logging.basicConfig(level=logging.DEBUG, format = '%(asctime)s %(levelname)s:%(message)s')
Output will get something like,
2018-03-08 19:30:00,066 DEBUG:this message will be ignored 2018-03-08 19:30:00,176 INFO:This should be logged 2018-03-08 19:30:00,201 WARNING:And this, too
Полиморфизм в Python
Это концепция, при которой функция может принимать несколько форм в зависимости от количества аргументов или типа аргументов, переданных функции.
В приведенном выше примере ключевое слово super используется для вызова метода родительского класса. Оба класса имеют метод show_salary. В зависимости от типа объекта, который выполняет вызов этой функции, выходные данные различаются.
Python также имеет встроенные функции, работающие с полиморфизмом. Одним из самых простых примеров является функция print в Python.
Вывод будет таким:
В приведенном выше фрагменте кода:
- Параметр конечного ключевого слова изменил работу функции print. Следовательно, «Привет!» не заканчивалось концом строки.
- len () в третьей строке возвращает int. Печать распознает тип данных и неявно преобразует его в строку и выводит его на консоль.
Проходите тест по Python и поймите, готовы ли вы идти на курсы
Overview of OOP Terminology
-
Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
-
Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods. Class variables are not used as frequently as instance variables are.
-
Data member − A class variable or instance variable that holds data associated with a class and its objects.
-
Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
-
Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
-
Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
-
Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.
-
Instantiation − The creation of an instance of a class.
-
Method − A special kind of function that is defined in a class definition.
-
Object − A unique instance of a data structure that’s defined by its class. An object comprises both data members (class variables and instance variables) and methods.
-
Operator overloading − The assignment of more than one function to a particular operator.
Python Objects and Classes
Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects.
An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
As many houses can be made from a house’s blueprint, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution
NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations
Аннотация
Курс DEV-PY200. Объектно-ориентированное программирование на языке Python направлен на изучение принципов объектно-ориентированного подхода при разработке приложений с использованием языка программирования Python.
Курс является логическим продолжением базовых курсов по процедурному программированию на языке Python.
Основные задачи курса:
- Введение понятия методов и переменных объекта;
- Изучение базовых концепций объектно-ориентированного программирования на языке Python»: инкапсуляция, наследование и полиморфизм;
- Перегрузка «магических» методов.
Курс DEV-PY200. Объектно-ориентированное программирование на языке Python позволяет совместно с курсами: DEV-PY100. Основы процедурного программирования на языке PythonDEV-PY110. Процедурное программирование на языке Python (расширенный курс)
подготовиться к сертификации PCAP – Certified Associate in Python Programming.
Знания и умения, полученные в результате обучения
В результате обучения на курсе слушатели будут знать и уметь:
• Создание пользовательского класса;• Построение иерархий классов;• Разработка «магических» методов;
Курсы, в освоении которых помогут приобретенные знания
-
DEV-PYWEB. Разработка WEB приложений на языке Python
-
DEV-PYQT. Разработка оконных приложений Python c использованием Qt
-
DEV-PYDF. Работа с различными форматами данных в Python
-
DEV-PYADMIN. Автоматизация задач системного администрирования
Давайте попрактикуемся



- obj.method()
- obj.atr



- надо определить класс
- создать объект
- обратиться к каждому из атрибутов, записав туда кастомные данные
- обратиться к каждому объекту, передав туда кастомные аргументы
на самом деле инициализатора, но мы в этой статье не будем углубляться в разницуВажно:
- метод __init__(), как и другие методы класса должен принимать как минимум 1 аргумент self
- к аргументам объекта можно обращаться из метода как аргументам self (например, self.arg)
- Если аргумент создаётся конструктором __init__, то его не нужно описывать в классе как отдельную переменную
Давайте создадим чуть более осмысленный класс.



Интересный эффект, который можно заметить — после пересоздания класса ранее созданные объекты не меняют своего поведения.


Геттеры и Сеттеры
- сеттер — setColor — проверяет, что передаётся строка и записывает её в атрибут color экземпляра. Если передан другой тип данных, возвращает ошибку.
- геттер — getColor — возвращает значение атрибута color текущего экземпляра

Наследование
- атрибуты: число ног, имя, возраст.
- методы: геттеры и сеттеры
- атрибуты: имя и т.п.
- методы: «говорение» (мяу) и т.п.


Такие классы ещё иногда называются «примесью», дальше станет понятно почему.
Удивительно, но это работает.
- наследник получает все методы и атрибуты обоих родителей.
- если у нескольких родителей есть одноимённые методы, то автоматически наследник получит методы того, кто раньше в списке (в нашем случае раньше был гео маркер, поэтому конструктор был унаследован от него, а не от организации).
Наследование от нескольких родителей иногда считается сомнительной практикой, будьте с ним аккуратны.
Переменные класса

- в атрибуте ID каждого объекта хранится его уникальный порядковый номер
- в переменной tag класса хранится число созданных объектов (тут надо быть осторожнее, так как возможно мы захотим уменьшать это число при удалении объекта).

Creating an Object in Python
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call.
This will create a new object instance named harry. We can access the attributes of objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of that class.
This means to say, since is a function object (attribute of class), will be a method object.
Output
<function Person.greet at 0x7fd288e4e160> <bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>> Hello
You may have noticed the parameter in function definition inside the class but we called the method simply as without any arguments. It still worked.
This is because, whenever an object calls its method, the object itself is passed as the first argument. So, translates into .
In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self. It can be named otherwise but we highly recommend to follow the convention.
Now you must be familiar with class object, instance object, function object, method object and their differences.
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random
Random Intro
Data Distribution
Random Permutation
Seaborn Module
Normal Distribution
Binomial Distribution
Poisson Distribution
Uniform Distribution
Logistic Distribution
Multinomial Distribution
Exponential Distribution
Chi Square Distribution
Rayleigh Distribution
Pareto Distribution
Zipf Distribution
NumPy ufunc
ufunc Intro
ufunc Create Function
ufunc Simple Arithmetic
ufunc Rounding Decimals
ufunc Logs
ufunc Summations
ufunc Products
ufunc Differences
ufunc Finding LCM
ufunc Finding GCD
ufunc Trigonometric
ufunc Hyperbolic
ufunc Set Operations