13 object oriented
13.1 basic concepts
- Class:
A class is a collection of abstract concepts of events with a series of common characteristics and behaviors. The concept described by class is very similar to that in real life. For example, there are many kinds of creatures, different kinds of food and different kinds of goods. And a class can be divided into various small classifications through subdivision, for example, animals can be divided into terrestrial animals, aquatic animals and amphibians, etc., which are divided into the same class, all of which have similar characteristics and behavior patterns.
- Instanced object
Instance object is usually defined as a specific individual of a certain kind of thing, which is a specific expression of this kind of thing. If human is a class, "Zhang San" is the instance object of human, because he represents a specific class individual.
- Class variable
class variables are generally defined in the class, but not in the class method. They can be used in the whole instantiated object.
- Class properties
class variable or instance variable, commonly used to describe the characteristics of the instance object, such as the name and height of Zhang San
- method:
in an informal way, a function defined in a class is called a method, which is often used to describe the behavior of an instance object. It is generally divided into a constructor and a regular function.
- inherit
it means that a subclass can obtain the properties and methods defined by the parent class from the parent class.
- Method override
if the method of the parent class cannot meet the requirements of the child class, you can define a method with the same name as the parent class. This process is called method Override (such as @ Override) or method Override in Java
- Instance variable
class is a very abstract concept, while instance represents a specific object, and the variables bound to the object can be called instance variables.
13.2 definition of category
A simple class definition format in Python is as follows:
class Person(object): """ //Define a human being """ # Class variable classVariable="sample" # Constructor, also called instantiation object method def __init__(self,name,age): self.name=name self.age=age # Methods defined in class def getPersonInfo(self): return f"name is {self.name},age is {self.age}"
detailed explanation is as follows:
- Define the keyword of a class as class
- Person: defined class name, initial must be uppercase
- (object): indicates the inherited parent class of the defined class, here is object
- The characters in the three quotation marks are document strings, which are used to describe the functions and functions of the class
- classVariable: a class variable that can be shared by all instance objects
- A kind of init_ : constructor, which is used to describe the characteristics of an object before instantiation
- name,age: the characteristics of the instantiated object itself
- getPersonInfo: a method defined in a class to describe the behavior of a class, usually starting with a verb
- self: represents the instantiated object itself, equivalent to this in Java/C ා
13.3 three characteristics of object-oriented
oriented to three common features: encapsulation, inheritance and polymorphism. They are as follows:
13.3.1 packaging
. Its main features are as follows:
- 1. The behavior of the object is invisible to the outside, that is, the state information of the object is private.
- 2. The client cannot change the internal state of the object through direct operation. Instead, the client needs to send a message to request the object to change its internal state. Object changes the internal state in a specific way according to the type of request to respond
- 3. In Python, the concept of encapsulation (the concealment of properties and methods) is not implicit, because it does not provide the keyword public/private/protected, such as C series language.
- Underline before:
The .
- Post underline
is usually used to solve naming conflicts. In Python, str is a function that converts other types to strings. If str is written_ , it can represent redefining a variable or method. In PyQT, there are many uses.
- Leading double underline
when used in the class environment, name rewriting will be triggered, which has special meaning for Python interpreter
- Double underline front and back
.
- Single offline
is often used as a temporary or meaningless variable name, or to represent the result of a previous expression in a Python REPL session.
13.3.2 succession
Inheritance usually means that a subclass obtains the data and methods of the parent class from the parent class, etc. Its main features are as follows:
- 1. Inheritance means that a class can inherit most functions of its parent class
- 2. Inheritance can reuse the functions defined by the parent class and extend the original functions of the parent class
- 3. Inheritance can use the hierarchy between objects of different classes to support multiple inheritance in Python.
13.3.3 polymorphism
. Before Peking Opera, the quintessence of Chinese culture, it was an art that passed down from generation to generation. Suppose there is a pair of father and son. The father is a very famous Peking Opera artist. When the son grows up, the play imitating the father is also lifelike. One day, my father was ill and couldn't come to the stage. My father's tickets for the theatre had been sold, and if they were refunded, the loss would be too great. Because Peking opera only comes to the stage after making up. Can a son take the place of his father? Here we need to pay attention to the following points:
- Subclass appears as parent
Her son acted for her father. After she put on makeup, she became a father.
- Subclasses must work in their own way
Son imitation is also imitation. He can only play his father's works with his own understanding
- When a subclass appears as a parent, its specific properties and methods cannot be used
After years of study, her son has actually developed his own unique performance mode and behavior habits. However, when he acts in place of his father, he cannot act in his own way. It must be performed in the father's style.
13.4 creating classes
let's create a class first. The example is as follows:
class Person: def __init__(self,name,age): self.name=name self.age=age def getPersonInfo(self): return f"name is {self.name},age is {self.age}" def run(self): return f"{self.name} is running"
13.5 create instance object of class
creating instance objects of a class is to create specific individuals according to the class, as shown below:
person=Person("Surpass",28)
Instance object. [property or method]
13.6 usage classes and examples
13.6.1 access properties
person=Person("Surpass",28) print(f"name is {person.name},age is {person.age}")
13.6.2 access method
person=Person("Surpass",28) print(f"person info is {person.getPersonInfo()}")
13.6.3 create multiple instances
since a class is an abstract collection of events, of course, n instance objects can also be created according to it, as shown below:
personA=Person("Surpass",28) personB=Person("Kevin",38) personB=Person("Lisa",20)
13.6.4 specifying default values for attributes
Each attribute in class must have an initial value. For some attributes that often do not need to be assigned each time, you can specify a default value as follows:
class Person: def __init__(self,name,age=28): self.name=name self.age=age def getPersonInfo(self): return f"name is {self.name},age is {self.age}" def run(self): return f"{self.name} is running" # Instanced object personA=Person("Surpass")
see if the above usage is similar to function usage.
13.6.5 modifying attribute values
if you need to modify the value of a property, you can use the following methods to modify it
- 1. Modify by example
- 2. Modify by calling method
1. Modify by example
The example code is as follows:
class Person: def __init__(self,name,age=28): self.name=name self.age=age def getPersonInfo(self): return f"name is {self.name},age is {self.age}" def run(self): return f"{self.name} is running" person=Person("Surpass",28) print(f"Before modify property {person.name} {person.age}") person.name="Lisa" person.age=20 print(f"After modify property {person.name} {person.age}")
The output is as follows:
Before modify property Surpass 28 After modify property Lisa 20
2. Modify by calling method
it is very convenient to modify attribute values directly through instance modification, as shown below:
class Person: def __init__(self,name,age=28): self.name=name self.age=age def getName(self): return self.name def setName(self,name): self.name=name def getAge(self): return self.age def setAge(self,age): self.age=age def getPersonInfo(self): return f"name is {self.name},age is {self.age}" def run(self): return f"{self.name} is running" person=Person("Surpass",28) print(f"Before modify property {person.name} {person.age}") person.setName("Lisa") person.setAge(20) print(f"After modify property {person.name} {person.age}")
The output is as follows:
Before modify property Surpass 28 After modify property Lisa 20
class Person: def __init__(self,name,age=28): self._name=name self._age=age @property def name(self): return self._name @name.setter def name(self,value): if not isinstance(value,(str,)): raise TypeError("Expect str") else: self._name=value @name.deleter def name(self): raise AttributeError("Can not delete attribute") @property def age(self): return self._age @age.setter def age(self,value): if not isinstance(value,(int,)): raise TypeError("Expect a numer") elif value<0: self._age=0 else: self._age=value @age.deleter def age(self): raise AttributeError("Can not delete attribute") def getPersonInfo(self): return f"name is {self.name},age is {self.age}" def run(self): return f"{self.name} is running" person=Person("Surpass",28) print(f"Before modify property {person.getPersonInfo()} ") person.name="Lisa" person.age=-123 print(f"After modify property {person.getPersonInfo()}") print(f"Test exceptions") person.name=98 person.age="098"
The output is as follows:
Before modify property name is Surpass,age is 28 After modify property name is Lisa,age is 0 //Test exceptions Traceback (most recent call last): File "C:/Users/Surpass/Documents/PycharmProjects/SADCI/TempCode/basicCode.py", line 52, in <module> person.name=98 File "C:/Users/Surpass/Documents/PycharmProjects/SADCI/TempCode/basicCode.py", line 15, in name raise TypeError("Expect str") TypeError: Expect str
? The answer, of course, is yes, as follows:
class Person: def __init__(self,name,age=28): self._name=name self._age=age def getName(self): return self._name def setName(self,value): if not isinstance(value,(str,)): raise TypeError("Expect str") else: self._name=value def delName(self): raise AttributeError("Can not delete attribute") def getAge(self): return self._age def setAge(self,value): if not isinstance(value,(int,)): raise TypeError("Expect a numer") elif value<0: self._age=0 else: self._age=value def delAge(self): raise AttributeError("Can not delete attribute") ageProperty=property(getAge,setAge,delAge) nameProperty=property(getName,setName,delName) def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" person=Person("Surpass",28) print(f"Before modify property {person.getPersonInfo()} ") person.setName("Lisa") person.setAge(-123) print(f"After modify property {person.getPersonInfo()}") print(f"Test exceptions") person.setName(98)
The output is as follows:
Before modify property name is Surpass,age is 28 After modify property name is Lisa,age is 0 //Test exceptions Traceback (most recent call last): File "C:/Users/Surpass/Documents/PycharmProjects/SADCI/TempCode/basicCode.py", line 49, in <module> person.setName(98) File "C:/Users/Surpass/Documents/PycharmProjects/SADCI/TempCode/basicCode.py", line 13, in setName raise TypeError("Expect str") TypeError: Expect str
. But in Python, if a class does not have a property, you can add a new property through the object. Property name, but this practice breaks the encapsulation feature in object-oriented, so it is not recommended. As follows:
class Person: def __init__(self,name,age=28): self._name=name self._age=age @property def name(self): return self._name @name.setter def name(self,value): if not isinstance(value,(str,)): raise TypeError("Expect str") else: self._name=value @name.deleter def name(self): raise AttributeError("Can not delete attribute") @property def age(self): return self._age @age.setter def age(self,value): if not isinstance(value,(int,)): raise TypeError("Expect a numer") elif value<0: self._age=0 else: self._age=value @age.deleter def age(self): raise AttributeError("Can not delete attribute") def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" person=Person("Surpass",28) # Add a new attribute directly through the instance, not recommended person.country="China" print(f"add new person property : {person.country}")
The output is as follows:
add new person property : China
13.7 properties
The attribute is often used to describe the characteristics of a class. It can be accessed through methods defined in the class, or through a class or instance. Therefore, attributes can be divided into class attributes and instance attributes.
13.7.1 instance properties
. An example code is as follows:
class Person: def __init__(self,name,age): # Instance property assignment self._name=name self._age=age # Get instance property value def getName(self): return self._name # Instance properties need to be bound to instance objects before they can be accessed person=Person("Surpass",28) print(f"{person.getName()}")
13.7.2 type properties
Python allows you to declare variables belonging to the class itself as class properties or class variables. Class properties do not need to instantiate objects, as follows:
class Person: # Class properties classVar="Class properties" def __init__(self,name,age): # Instance property assignment self._name=name self._age=age # Get instance property value def getName(self): return self._name # Instance properties need to be bound to instance objects before they can be accessed person=Person("Surpass",28) # Access instance properties - via instance print(f"Access instance properties-By example:{person.getName()}") # Access class properties - pass instance print(f"Access class properties-General examples:{person.classVar}") # Access class properties print(f"Access class properties:{Person.classVar}")
The output is as follows:
Access instance properties - via instance: Surpass Access class properties - pass instance: class properties Accessing class properties: class properties
13.7.3 private property
ාlanguage permission control fields, such as public/protected/private, etc., are not available in Python. The general convention is that the properties defined at the beginning of a single underscore are private properties, as follows:
class Person: # Class private property _classVar="Class properties" def __init__(self,name,age): # Instance property assignment self._name=name self._age=age
13.7.4 special properties
Python objects contain many methods that start and end with double underscores, which are called special properties. Common special properties are as follows:
Special methods | meaning | Example |
---|---|---|
obj. __dict__ | Object's property dictionary | int.__dict__ |
instance.__class__ | Class to which the object belongs | int.__class__ |
class.__bases__ | Base tuple of class | int.__bases__ |
class.__base__ | Base class of class | int.__base__ |
13.7.5 summary
- 1. Instance properties can only be accessed through instance objects
- 2. Class attribute belongs to the variable shared by class and instance object, which can be accessed without instantiation. In the instantiated object, it can also be accessed through instance object
- 3. If you want to define a private property, just underline the variable
- 4. In principle, the encapsulation feature of object-oriented programming requires no direct access to the properties in the class. In Python, you can access and modify the private properties by defining the private properties, and then defining the corresponding methods. You can also use the decorator @ property to decorate these functions, so that the program can access the functions as properties.
13.8 succession
creating a class does not need to be created every time. If you have a class that already has the functionality to meet your needs, you can use inheritance to do that. When a class inherits another class, it will automatically get the properties and methods of another class. The original class is called the parent class, and the new class is called the child class. In addition to inheriting the properties and methods of the parent class, the child class can also define its own properties and methods, or override the methods of the parent class.
13.8.1 construction method_ init_ ()
when creating an instance of a subclass, Python first needs to complete the task of assigning values to all the properties of the parent class. So subclass method_ init_ () need help from parent. As follows:
1. Explicitly call the parent class construction method
class Person: def __init__(self,name,age): self._name=name self._age=age def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): def __init__(self,name,age,): super().__init__(name,age) student=Student("Surpass",25) print(student.getPersonInfo())
The output is as follows:
name is Surpass,age is 25
details of the above codes are as follows:
- super()._init_(name,age): explicitly declare to call the parent class construction method. If the child class has no special property, it can also be omitted
- student.getPersonInfo(): subclass calls the method inherited from the parent class
2. Explicitly call the parent class construction method and add its own properties
An example of is as follows:
class Person: def __init__(self,name,age): self._name=name self._age=age def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): def __init__(self,name,age,classNumber): super().__init__(name,age) self._classNumber=classNumber def getStudentInfo(self): return f"name is {self._name},age is {self._age},classNumer is {self._classNumber}" student=Student("Surpass",25,"Class-NO.1") print(student.getStudentInfo())
The output is as follows:
name is Surpass,age is 25,classNumer is Class-NO.1
3. Implicitly call the parent class construction method
An example of is as follows:
class Person: def __init__(self,name,age): self._name=name self._age=age def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): pass student=Student("Surpass",25) print(student.getPersonInfo())
The output is as follows:
name is Surpass,age is 25
? Take a look at the following example:
1. Both parent and child classes have their own constructors defined
class Person: def __init__(self,name,age): self._name=name self._age=age print("1.Call the parent class constructor") def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): def __init__(self,name,age,classNumber): self._name=name self._age=age self._classNumber=classNumber print("2.Call subclass constructor") def getStudentInfo(self): return f"name is {self._name},age is {self._age},classNumer is {self._classNumber}" student=Student("Surpass",25,"Class-No.1")
The output is as follows:
2. Call subclass construction method
2. The parent class has its own constructor defined, while the child class does not
class Person: def __init__(self,name,age): self._name=name self._age=age print("1.Call the parent class constructor") def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): pass
The output is as follows:
1. Call the parent class construction method
3. Both the parent class and the child class have their own constructors defined, but the child class explicitly calls the parent class construction method
class Person: def __init__(self,name,age): self._name=name self._age=age print("1.Call the parent class constructor") def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): def __init__(self,name,age,classNumber): super().__init__(name,age) self._classNumber=classNumber print("2.Call subclass constructor") def getStudentInfo(self): return f"name is {self._name},age is {self._age},classNumer is {self._classNumber}" student=Student("Surpass",25,"Class-NO.1")
The output is as follows:
1. Call the parent class construction method 2. Call subclass construction method
through the above codes, the following conclusions can be concluded:
- 1. If the constructor is not defined in the subclass, the parent constructor is implicitly called
- 2. If the parent constructor is explicitly declared to be called in a subclass, the parent constructor shall be called first, and then the constructor of the subclass
- 3. If the subclass defines its own constructor, only the constructor of the subclass itself will be called
- 4. If you need to call the parent constructor explicitly, you can use the super keyword
- 5. Be good at using super method, which can simplify the code. When you want to call the parent class construction method or ordinary method, you can use this keyword
13.8.2 subclass definition properties and methods
when a class inherits from the parent class and the function of the parent class cannot meet its own needs, the child class can define its own properties and methods, as shown in the following example:
class Person: def __init__(self,name,age): self._name=name self._age=age print("1.Call the parent class constructor") def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): def __init__(self,name,age,classNumber): super().__init__(name,age) # Properties defined by subclass itself self._classNumber=classNumber print("2.Call subclass constructor") # Method defined by subclass itself, explicitly calling parent method def getStudentInfo(self): return super().getPersonInfo() # Method of subclass self definition def getStudentCount(self): studentList=[] studentList.append(self._name) return len(studentList)
The output is as follows:
1. Call the parent class construction method 2. Call subclass construction method Result of calling parent method: name is bypass, age is 25 Call the method of the subclass itself: student count is 1
13.8.3 override parent method
it's very simple to override the parent method in Python. You only need to make the method name in the subclass consistent with the parent name, as shown below:
class Person: def __init__(self,name,age): self._name=name self._age=age print("1.Call the parent class constructor") def getPersonInfo(self): return f"name is {self._name},age is {self._age}" def run(self): return f"{self._name} is running" class Student(Person): def __init__(self,name,age,classNumber): super().__init__(name,age) # Properties defined by subclass itself self._classNumber=classNumber print("2.Call subclass constructor") # Methods of subclass self definition def getStudentCount(self): studentList=[] studentList.append(self._name) return len(studentList) # Override the methods defined by the parent class def getPersonInfo(self): return f"name is {self._name},age is {self._age},class number is {self._classNumber}" student=Student("Surpass",25,"Class-NO.1") print(f"Call the method of the subclass itself: student count is {student.getStudentCount()}") print(f"Call a subclass to override the method of the parent class:{student.getPersonInfo()}")
The output is as follows:
1. Call the parent class construction method 2. Call subclass construction method Call the method of the subclass itself: student count is 1 Call subclass to override the method of parent class: name is bypass, age is 25, class number is class-no.1
13.8.4 multiple inheritance
ාand other languages are single inheritance (that is, a class can only inherit one parent class at the same time) and multi interface inheritance (that is, a class can inherit multiple interfaces), multi-level inheritance (because the inherited parent class inherits from other parent classes, it seems that there are multiple levels), multiple inheritance is supported in Python (that is, a class can inherit multiple classes at the same time), as shown in the following example:
class A: def __init__(self): print("1.Construction method of parent class-1") def getMethonA(self): print(f"1.Parent method{self.getMethonA.__name__}") class B: def __init__(self): print("2.Construction method of parent class-2") def getMethonB(self): print(f"2.Parent method{self.getMethonB.__name__}") class C: def __init__(self): print("3.Construction method of parent class-3") def getMethonC(self): print(f"3.Parent method{self.getMethonC.__name__}") class D(A,B,C): def getMethonD(self): print(f"4.Subclass method{self.getMethonD.__name__}") d=D() d.getMethonA() d.getMethonB() d.getMethonC() d.getMethonD()
The output is as follows:
1. Parent class construction method-1 1. Parent method getMethonA 2. Parent method getMethonB 3. Parent method getMethonC 4. Subclass method getMethonD
There are good and bad ways to use multiple inheritance
1. The advantage is that it can call methods of multiple parent classes
2. The disadvantage is that if multiple inherited parent classes belong to the same parent class, there will be ambiguity, which will also increase the logical complexity. Therefore, multiple inheritance is not recommended
13.9 method
The method is a class related function. Python is used to define a method format as follows:
def method name (self, parameter 1, parameter 2...): "" "function description" "" Function body Return return value
The definition of method is the same as the previous function. The only difference is that the first position of the parameter must be self. Python methods are often divided into construction methods, common methods, class methods and static methods.
13.9.1 construction method
The constructor is usually used to pass some necessary property values to an object before instantiating it. Usually, the__ init__ () as an identifier, the general format is as follows:
class Person: # Construction method def __init__(self,name,age): self._name=name self._age=age
13.9.2 general methods
methods other than construction methods, class methods and static methods are called ordinary methods, which are generally defined by users themselves. Examples are as follows:
class Person: # Construction method def __init__(self,name,age): self._name=name self._age=age # Common method def getName(self): return self._name person=Person("Surpass",28) print(f"To access the normal method:{person.getName()}")
The output is as follows:
Access common method: Surpass
13.9.3 methods
@classmethod def method name (cls, parameter 1, parameter 2...): Function body Return return value
The example code is as follows:
class Person: className="This is a class property" # Construction method def __init__(self,name,age): self._name=name self._age=age # Common method def getName(self): return self._name # Class method, which can access class properties but not object properties @classmethod def getPersonInfo(cls,hello="Hello,"): return f"{hello} {cls.className} " person=Person("Surpass",28) print(f"To access common methods:{person.getName()}") print(f"Access class methods:{Person.getPersonInfo('Welcome, ')}")
The output is as follows:
Access common method: Surpass Access class method: Welcome, this is the class property
13.9.4 static method
. Static methods are a little like tools attached to class objects. Different from ordinary methods, when calling static methods, they can only be used through class objects or instance objects, but not separated from class objects, that is, static methods are bound in class objects. The syntax format is as follows:
@staticmethod def method name (Parameter1, parameter2...): Function body Return return value
The example code is as follows:
class Person: className="This is a class property" # Construction method def __init__(self,name,age,height,weight): self._name=name self._age=age self._height=height self._weight=weight # Common method def getName(self): return self._name # Class method, which can access class properties but not object properties @classmethod def getPersonInfo(cls,hello="Hello,"): return f"{hello} {cls.className} " # Static method, class properties are not accessible @staticmethod def getBMI(h,w): return w/((h/100)**2) # Common method def showBMI(self): bmi=self.getBMI(self._height,self._weight) return bmi person=Person("Surpass",28,170,59) print(f"To access common methods:{person.getName()}") print(f"Access class methods:{Person.getPersonInfo('Welcome, ')}") print(f"To access static methods:{Person.getBMI(170,59)}") print(f"Access through instance object:{person.showBMI()}")
The output is as follows:
Access common method: Surpass Access class method: Welcome, this is the class property Access static method: 20.41522491349481 Access through instance object: 20.41522491349481
13.9.5 summary
- 1. Class method and static method are realized by decorator, but construction method and common method are not prosperous
- 2. Ordinary methods need to define self parameters explicitly, class methods need to define cls parameters, and static methods don't need self and cls parameters
- 3. Ordinary methods can only be called through instance objects. Class methods and static methods can be called through class objects or instance objects. If class methods and static methods are called by instance objects, they will eventually be called through class objects
- 4. Common methods are the most commonly used, which can directly process various logics of instance objects; class methods do not need to create instance objects, but directly process class object logics; static methods extract part of the logic related to class objects, which can be used for testing and convenient for later maintenance of code
- 5. common methods and class methods can change the state of instance objects or class objects, while static methods cannot.
Address: https://www.cnblogs.com/surpassme/p/12983492.html
This article is synchronously published on wechat subscription number. If you like my article, you can also pay attention to my wechat subscription number: woaitest, or scan the following QR code to add attention: