Python Chapter 4 object oriented

object-oriented

1. Overview (just understand)

# Object Oriented Programming (OOP) is a programming idea and a design and programming method to solve software reuse.
# The essence is an abstract thinking process embodied in the establishment of a model. The model is used to reflect the characteristics of things in the real world.
# Any kind of thing can be regarded as an object, "everything is an object", and the object contains data and functions that operate data.
# For example, in practical application, a person can be abstracted into a class, which contains a person's "name, age, gender" and other information.
# Python is a typical object-oriented language. The data in Python are objects.

Object oriented: abstract problems, classify and encapsulate functions, and treat relevant data and methods as a whole.
Reduce the coupling between codes and emphasize the idea of module development.
The functions of free splitting and combination are embodied in different combination forms, so as to provide different services.

# Class: a collection of objects that describe the same properties and methods. Defines the properties and methods common to each object in the collection. An object is an instance of a class.
# Object: an instance of a data structure defined by a class.
# Instantiation: create an instance of a class and the specific object of the class.
# Class members: including properties, methods, etc.
# Inheritance: that is, a derived class inherits the properties and methods of the base class.
# Method Rewriting: if the method inherited from the parent class cannot meet the needs of the child class, it can be rewritten. This process is called method override, also known as method rewriting.

2. Creation and use of classes

Construction method

Underscores before variable and method names


3. Members of the class

Properties and methods are collectively referred to as members of a class

1. Properties

Object properties
Object properties, also known as instance properties, are usually__init__Initialization in
# Create class
class Person:
    # Construction method
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('Xiao Wu', 16)
print(p.age)#16
p.age+=1
print(p.age)#17
Class properties
Class attribute: class attribute is the attribute of the class itself, no matter how many objects are created according to the class,
There is still only one class attribute, so class attributes can be shared between objects.
It is similar to static public variables in some other high-level languages.
***The difference is Python Objects can also call class properties.***

# Create class
class Person:
    info = 'this is a person.'
    # Construction method
    def __init__(self, name, age):
        self.name = name
        self.age = age  
p = Person('Xiao Wu', 16)
print(p.info)

In addition to defining attributes inside the class, attributes can also be defined outside the class

# Create class
class Person:
    info = 'this is a person.'
    # Construction method
    def __init__(self, name, age):
        self.name = name
        self.age = age  

Person.gender = 'unknown'
print(Person.gender) #unkonwn

If the property is private, the identifier cannot be used directly Attributes can be modified or queried, but attributes can be modified indirectly through functions.

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

def getinfo(self):
    info = self.__name + ' ' + str(self.__age)
    print(info)
p = Person('Xiaoyue', 16)
print(p.__name)  # report errors
p.getinfo()
 print(p.__name)  # report errors
AttributeError: 'Person' object has no attribute '__name'
class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def getinfo(self):
        info = self.__name + ' ' + str(self.__age)
        print(info)

    def setage(self, age):
        self.__age = age


p = Person('Xiaoyue', 16)
p.setage(17)
p.getinfo()
Age: 0
stu full name: Unkonw,Age:0
stu Name: Zhang San,Age: 18
stu Name: Li Si,Age: 18
 Xiaoyue 17
Decorator @ property

What is a decorator??

In fact, decorator is a closure, and decorator is an application of closure.
What is a decorator? In short, python Decorator is a function used to expand the function of the original function,
The special feature of this function is that its return value is also a function,
use python The advantage of decorator is to add new functions to the function without changing the code of the original function.

The function of decorator @ property is to encapsulate the function properties of a class into similar data properties

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = None
    @property
    def age(self):#Modify the age() method with @ property, so that the method becomes the getter method of the age attribute (but the age attribute is read-only at this time)
        print('get age')
        return self._age
    @age.setter
    def age(self, age):#To modify the value of the age attribute, you also need to add a setter method. In this case, you need to use the setter decorator
        print('set age')
        self._age = age
p = Person('petty thief', 16)
p.age = 17
print(p.age)
get age
None

2. Method

(1) Example method
Common method

It can be called whenever and wherever

Private method

Methods decorated with double underscores can only be called inside a class

class Person:
    # Define the construction method of this class
    def __init__(self, name, age):
        self.name = name
        self.age = age
    # Define the output object information of the member method of this class
    def show(self):
        print('full name:', self.name)
        print('Age:', self.age)
    def __showage(self):
        print('Age:', self.age)
    
p=Person('Passerby a',18)
p.show()
# Person.__showage()#report errors
    Person.__showage()
AttributeError: type object 'Person' has no attribute '__showage'
(2) Static method

What is a static method?
Static methods are decorated with the decorator @ staticmethod. There are no self and cls parameters (other parameters are optional), but any properties and methods of the class or instance cannot be used in the method body.
Both classes and objects can call static methods.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @staticmethod
    def getinfo():
         print('Class Person')
# main entry
if __name__ == '__main__':
    p = Person(''Xiaoyue'', 16)
    p.getinfo()
    Person.getinfo()
Class Person
Class Person
#Although both classes and instances can call static methods, when an instance calls a static method, the class is actually calling the static method
(3) Class method

What is a class method?
Class method is a method decorated with decorator @ classmethod. It is specified that the first parameter of class method must be exclusive to the current class, that is, cls represents the current class rather than the instance object. This method is generally agreed as "cls", and attributes and methods are passed through cls (attributes and methods of instances cannot be passed)

class Person:
    info = 'Class Person'
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print(self.info)
    @classmethod
    def getinfo(cls):
        print(cls.info)
# main entry
if __name__ == '__main__':
    p = Person('Xiaoyue', 16)
    p.getinfo()
    Person.getinfo()

Class Person
Class Person
Class Person
#Although both classes and instances can call class methods, when instances call class methods, the class is actually calling this class method.

4. Succession

Python inherits the parent class through (), and subclasses can override and override the methods of the parent class, or have their own unique methods.
When you want to override the method of the parent class in the subclass, you should first introduce the method with the same name of the parent class. There are two methods to achieve the purpose of inheritance.

1. Call unbound parent method

2. Use super function

Multiple inheritance

Java and C# can only inherit one class, but Python can inherit multiple classes. There are two forms of name object calling search method, one is depth first and the other is breadth first. Python3.x uses breadth first, which is also called masonry inheritance problem.

 	A
   / \
  B   C
   \ /
    D
 At this time, the search order is D->B->C->A
```cpp
class Plant():
    def __init__(self):
        print("Enter plant")
        print("Leave plant")

class Fruit(Plant):
    def __init__(self):
        print("Enter Fruit")
        super().__init__()
        print("Leave Fruit")

class Vegetable(Plant):
    def __init__(self):
        print("Enter vegetable")
        super().__init__()
        print("Leave vegetable")

class Tomato(Fruit, Vegetable):
    def __init__(self):
        print("Enter Tomato")
        super().__init__()
        print("Leave Tomato")

tomato = Tomato()


# output
# Enter Tomato
# Enter Fruit
# Enter vegetable
# Enter plant
# Leave plant
# Leave vegetable
# Leave Fruit
# Leave Tomato

Other common methods in class

1.new

__ new__ Method is called before the instance is created, because its task is to create the instance and then return the instance. It is a static method.
That is__ new__ Yes__ init__ Previously called__ new__ The return value (instance) of will be passed to__ init__ Method, and then__ init__ Set some parameters for this instance.

#__ new__ There must be at least one parameter cls, which represents the class to be instantiated. This parameter is automatically provided by the Python interpreter during instantiation

#__ new__ You must have a return value and return the instantiated instance. This is implemented by yourself__ new__ You should pay special attention when you return the parent class__ new__ An instance of the object, or directly an object__ new__ Examples

#__ init__ There is a parameter self, which is this__ new__ Returned instance__ init__ In__ new__ Some other initialization actions can be completed on the basis of__ init__ No return value is required

#We can compare this class to a manufacturer__ new__ The method is to purchase raw materials in the early stage__ init__ The method is to process and initialize commodity links on the basis of raw materials

Built in function

1.instance function:

Judge whether an object is a specified class or a subclass of a specified class.

2.issubclass function

Determine whether a class is a subclass of another class

3.type function

Used to get the class to which an object belongs

class Person:  # Define the Person class
    pass


class Student(Person):  # Define the subclass Student with Person as the parent class
    pass

class Flower:  # Define the Flower class
    pass
stu = Student()  # Create Student class object stu
f = Flower()  # Create a Flower object f
print(isinstance(stu, Person))#Determine whether stu is a Person class or its subclass object
print(isinstance(f, Person))
print(issubclass(Student, Person))
print(type(f))
True
False
True
<class '__main__.Flower'>```

Object oriented advanced applications

Dynamically extending classes and instances

What does that mean?
As a dynamic language, Python can not only define properties and methods when defining classes, but also dynamically bind new properties and methods for the exclusive created.

Import is required when adding dynamic methods types.MethodType
from types import MethodType
class Student:
    pass
def SetName(self,name):
    self.name=name
def SetSno(self,sno):
    self.sno=sno
stu1=Student()
stu2=Student()
stu1.SetName=MethodType(SetName,stu1)#Add method SetName for instance stu1
Student.SetSno=SetSno#Add method SetSno for Student class
stu1.SetName("Zhang San")
stu2.SetName("123123")#An error will be reported because the SetName method is only added to the instance stu1 rather than the class Student
# AttributeError: 'Student' object has no attribute 'SetName'
stu1.SetSno('2001113')

But here comes the problem

# python is a dynamic language: you can modify code while it is running.
# For example, add attributes to objects and methods to classes.
# However, if it is added or modified arbitrarily without constraints, there is no guarantee for the robustness and security of the program.
# In actual development, when adding attributes to an instance for constraints, Python allows you to define class es,
# Define a special__ slots__ Variable to limit the attributes that can be added to the class instance.
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        #Pay attention here__ slots__ The arguments in the function are wrapped with ''
    __slots__ = ("name", "age")
class Student(Person):
    def __init__(self, name, sex, age):
        super().__init__(name, age)
        self.sex = sex
p1 = Person("tom", 18)
# p1.sex = "male"Person cannot add other attributes
#AttributeError: 'Person' object has no attribute 'sex'
stu1 = Student("jack", "male", 22)
print(stu1.name, stu1.sex, stu1.age)
stu1.country = "china"
print(stu1.country)  # Although the parent class settings__ slots__ Attribute constraints, but not for subclasses.

Metaclass

Everything in python is an object, so an object has a corresponding 'Class' or' type '
The type of object is: class
The type of class is meta class, which is also type
Type or type

class Student: #Define Student class
   pass
stu=Student() #Defines the object stu of the Student class
print('stu The category is',stu.__class__) #Use__ class__ Property to get the class to which it belongs
print('Student The category is',Student.__class__)

stu The category is <class '__main__.Student'>
Student The category is <class 'type'>

Duck type

# "When you see a bird walking like a duck, swimming like a duck and barking like a duck, then the bird can be called a duck."
# In duck type, the focus is on the behavior of the object and what it can do; Instead of focusing on the type of object.

Keywords: Python

Added by bskauge on Fri, 25 Feb 2022 15:12:03 +0200