Object-oriented advanced course, is to talk about the three characteristics of object-oriented: encapsulation, inheritance, polymorphism
@property decorator
Although not recommended python properties and methods are set to private, but fully exposed to the outside world is not good, so we give the property assignment can not guarantee the validity of nine, therefore, in order to make safe and convenient access to the property, you can the operation performed by the corresponding attribute getter (accessor) and setter (modifier) method, in python may be considered to use the packaging wrapper @property getter and setter methods
class Person(object): def __init__(self,name,age): self._name=name self._age=age #访问器 - getter方法 @property def name(self): return self._name @property def age(self): return self._age # 修改器 - setter方法 @age.setter def age(self,age): self._age=age def play(self): if self._age <= 16: print( " % S being played blowing bubbles! " % Self._name) the else : Print ( " chess being played% s! " % Self._name) DEF main (): Person = the Person ( " wangbb " , 16 ) Person .play () # call setter modify modify its properties person.age = 21 person.play () # person.name = 'WBB' #AttributeError: CAN not attribute the SET IF __name__ == ' __main__ ' : main ()
Under the effect of the FIG:
__slots__ magic
__slots__ magic is to make this dynamic python language, limit our custom type can only bind to a specific property, and only take effect for the current class, its subclasses no limiting effect
class Person (Object): # define Person class only bind _name, _age, _gender attributes # Note here that, the _name not the same name and an attribute, the attribute name can not bind __slots__ is = ( ' the _name ' , ' _age ' , ' 's _gender ' ) # the Person class initialization DEF the __init__ (Self, name, Age): self._name = name self._age = Age # accessor - getter method @Property DEF name (Self): return self._name @Property defAge (Self): return self._age # Modifier - setter Method @ age.setter DEF Age (Self, Age): self._age = Age DEF Play (Self): IF self._age <= 16 : Print ( " % s being played blowing bubbles! " % self._name) the else : Print ( " % s are playing chess! " % self._name) DEF main (): Person = the Person ( " wangbb " , 16 ) person.play () # Call the setter modify modify its properties person.age = 21 person.play () person._gender = ' M ' # person._isgay = True AttributeError: 'the Person' Object attribute has NO '_isgay' IF __name__ == ' __main__ ' : main ()
Static methods and class methods
There are three methods defined in the class: object methods (mostly in front of the object method), a static method, a class method. On the static method, for example: We define a "triangle" class, is constructed by the incoming three triangular side length, and a method to calculate the perimeter and area, but not the long sides of the incoming three triangular objects can be constructed so we could start with a way to verify whether the three side lengths can form a triangle, it is clear that this method is not an object method, because the triangular object when calling this method has not been created out (do not know because the three sides can form a triangle) , so this method belongs to the triangle-like object and are not part of the triangle. We can use the static method to solve this problem:
from math import sqrt class Triangle(object): def __init__(self,a,b,c): self._a=a self._b=b self._c=c #静态方法 @staticmethod def is_valid(a,b,c): return a + b > c and a + c > b and b + c > a def perimeter(self): return self._a+self._b+self._c def area(self): hrefself.perimeter = () / 2 return sqrt (the href * (the href-self._a) * (the href-self._b) * (href- self._c)) DEF main (): A, B, C =. 3, 4,5 # static methods and class methods are invoked by a message to the class of IF Triangle.is_valid (a, B, C): triangle = triangle (a, B, C) Print ( " triangle perimeter is: " , triangle.perimeter ()) # can also give a message to call the object class method it is to be the object receiving the incoming message as a parameter Print (Triangle.perimeter (triangle)) Print ( " area of the triangle is: " , triangle .area ()) Print (Triangle.area (Triangle)) the else : Print ( " Sorry, could not form a triangle! " ) IF the __name__ == ' __main__ ' : main ()
And more similar to the static method, Python can also agree in the first parameter defined in the class class methods, class methods named cls, it represents the current class of objects related information (class itself is a target, and some places metadata object called a class), this parameter we can get information and related classes and objects can create a class:
from time import time, localtime, sleep class Clock(object): """数字时钟""" def __init__(self, hour=0, minute=0, second=0): self._hour = hour self._minute = minute self._second = second @classmethod def now(cls): ctime = localtime(time()) return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec) def run(self): """走字""" self._second += 1 if self._second == 60: self._second = 0 self._minute += 1 if self._minute == 60: self._minute = 0 self._hour += 1 if self._hour == 24: self._hour = 0 def show(self): """显示时间""" return '%02d:%02d:%02d' % \ (self._hour, self._minute, self._second) defmain (): # create an object class by obtaining a method and system time Clock = Clock.now () the while True: Print (clock.show ()) SLEEP ( . 1 ) clock.run () IF the __name__ == ' __main__ ' : main ()
Relations between classes
Simply put, the relationship between class and class, there are three: is-a, has-a and use-a relationship.
- is-a relationship, also known as inheritance or generalization, such as relationships, the relationship between students and the people of mobile phones and electronic products belong to the inheritance.
- has-a relationship is usually called the association, such as the relationship between departments and employees, the relationship between the car and the engine belong to the association; association if the association and is an integral part of, then we call aggregation relationship; if further responsible for the overall life cycle (whole and indivisible part of, but also with the demise) section, then this is the strongest correlate of relationship we call synthesis.
- use-a relationship is usually referred to rely on, such as the driver acts (method) of a drive, which (parameters) to use the car, then the relationship between the driver and the car is the dependencies.
Inheritance and polymorphism
python can create a new class on the basis of existing classes, a practice which is to make a class where it will directly inherit properties and methods from another class down, thereby reducing write duplicate code. Provide information to inherit what we call the parent class, also called the superclass or base class; subclass inherits get what we call information, also called the derived class or derived class. In addition to the subclass inherits the properties and methods of the parent class provides, you can also define your own unique properties and methods, so the child analogy more capacity owned by the parent class, subclass inherits the parent class, parent class can has given way to the realization of the new version, called the action method overrides (override). By rewriting method we can make the same behavior of the parent class has a different version in a subclass to achieve, when we call passes this subclass rewritten, different subclasses of objects exhibit different behavior, this is the polymorphism (poly-morphism).
Python does not provide the grammatical level like Java or C # as support for the abstract class, but we can abc
module ABCMeta
metaclasses and abstractmethod
to achieve the effect of an abstract class wrapper, if there is an abstract method then this class in a class will not be able to instantiate of (create an object).
from abc import ABCMeta,abstractmethod class employee(object,metaclass=ABCMeta): def __init__(self,name): self._name=name @property def name(self): return self._name @abstractmethod def get_salary(self): pass class manger(employee): def get_salary(self): return 15000.0 class programer(employee): def __init__(self,name,work_hour=0): super().__init__(name) self._work_hour=work_hour def get_salary(self): return 150.0*self._work_hour @property def work_hour(self): return self._work_hour @work_hour.setter def work_hour(self,work_hour): self._work_hour=work_hour if work_hour>0 else 0 class salesman(employee): def __init__(self,name,sales=0): super().__init__(name) self._sales=sales def get_salary(self): return 1200.0+self._sales*0.05 @property def sales(self): return self._sales @sales.setter def sales(self,sales): self._sales=sales if sales >0 else 0 def main(): emps=[manger('wbb'),programer('bb'),salesman('lj')] for emp in emps: if: isinstance (emp, programer) emp.work_hour (the INPUT (= int " long Please enter the% s job this month: " % emp.name)) elif isinstance (emp, Salesman): emp.sales = float (the INPUT ( " Please enter% s sales this month: " % emp.name)) Print ( " % s month salary: ¥% s yuan " % (emp.name, emp.get_salary ())) IF __name__ == ' __main__ ' : main ()