Article From:https://www.cnblogs.com/hechengwei/p/9061453.html

I. Object oriented design

  Object oriented design is a process that integrates data and actions of a specific class of things together, and does not require object oriented programming, but if you want to construct data types with object properties and features, more considerations are needed.

def dog(name,gender,type):
    def call_dout(dog):
        print("A dog [%s], Wang Wangjiao"%name)
    def eat_meat(dog):
        print("A [%s], eating meat" %type)
    def init(name,gender,type):
        dog1={
            "name":name,
            "gender":gender,
            "type":type,
            "jiao":call_dout,
            "chirou":eat_meat,
        }
        return dog1
    return init(name,gender,type)
d1=dog("dagouxiong","gong","zangao")
print(d1)
d1["call_out"](d1)
d1["eat_meat"](d1)

 

Two, class and object

1.class

  A class is an abstract concept, a data structure used to describe a class of things (things are the combination of data and action), which are used to produce real objects (instances).

2.object

  The object can be understood as a concrete thing (a collection of data and actions).

3.Class and object

  Objects are generated by classes, which can be regarded as a template, and objects are generated by the template of class.

4.instantiation

  The process of generating objects from a class is instantiated, and the result of instantiation is an object, or an instance.

Three, class

1.Declarations class

  Declarative classes are very similar to declarative functions.

'''
class Class names:"Class document string"Class body'''
class Data:#title case
    pass
d1 = Data()#Generating an object D1 by instantiation of the class Data

 

2.New type and classical class

(1)New classes and classic classes are distinguished only in Python2, and Python3 is new.

(2)Difference: new classes must inherit at least one parent

(3)All classes have a default inherited object parent class.

(4)Python2A different form of representation of a classic class and a new class

#Classical class
class Data:
    pass
#new-style class
class Data(Father):
    pass

  Python3Both of the two forms are new.

3.attribute

  Attributes are divided into data attributes and function attributes. Classes and objects access their attributes through points.

(1)Data attributes: Variables

(2)Function attribute: function, in object oriented, it is also called method.

4.Data attributes of a class

  The data attribute of a class is also known as static or static data, which is bound to its class and does not depend on any instance.

class Chinese:
    country = "China"#Data attributes
    def __init__(self,name):
        self.name  = name
    def play_ball(self,ball):
        print("%s%s is playing."%(self.name))

5.The functional properties of a class (also known as a method)

  Naming rules (verb + nouns)

class Chinese:
    country = "China"def play_ball(self,ball):#Function attribute
        print("Playing ball")

6.View class properties

  Two ways to see the attribute of a class: (1) dir (class name), the result is a list of names; (2) class name.__dict__: the result is a dictionary, key is the attribute name, and value is the attribute value

class American:
    "This is an American class"
    sport = "basketball"
    def __init__(self,name,age,gender):
        self.name=name
        self.age=age
        self.gender=gender
    def play_basketball(self):
        print("Put in a three point ball")
print(American.__dict__)
print(dir(American))
#Special class attributes
print(American.__name__)#The name of the class: American
print(American.__doc__)#The document string of the class: This is an American class
print(American.__base__)#The first class of the class: < class'object'>
print(American.__bases__)#The tuple formed by all parent classes: (< class'object'>).
print(American.__module__)#The class definition is in the module: __main__
print(American.__class__)#The class corresponding to the instance: < class'type'>

Four. Objects

1.instantiation

  Objects are instantiated by class, and the result of instantiation is called an object or instance, and the data attributes of a custom instance can be used as a built-in method of the class __init__ (), which is automatically executed when the class is instantiated.

class American:
    "This is an American class"
    sport = "basketball"
    def __init__(self,name,age,gender):#The instantiation process can simply understand how I execute the function, and the instance itself will pass the parameter to self (this is the default step).
        self.name=name
        self.age=age
        self.gender=gender
    def play_basketball(self):
        print("Put in a three point ball")
a1 = American("Kobe",38,"male")

2.View the instance property

  The same as the view class attribute, dir (instance name) and instance name.__dict__

class American:
    "This is an American class"
    sport = "basketball"
    def __init__(self,name,age,gender):
        self.name=name
        self.age=age
        self.gender=gender
    def play_basketball(self):
        print("Put in a three point ball")
a1 = American("Kobe",38,"male")
print(a1.__dict__)
print(dir(a1))

  Note: do not modify the dictionary returned by __dict__

3.The addition, deletions and deletions of class and instance attributes

(1)Adding or deletions of class attributes

class Chinese:
    country = "China"
    def __init__(self,name):
        self.name  = name
    def play_ball(self,ball):
        print("Playing ball")
print(Chinese.country)#check
Chinese.country="China"#change
Chinese.location="Asia"#increase
del Chinese.country#Delete

(2)Increasing and deletions of instance attributes

class Chinese:
    country = "China"
    def __init__(self,name):
        self.name  = name
    def play_ball(self,ball):
        print("%sPlaying ball"%(self.name,ball))
p1 = Chinese("dazui")
print(p1.__dict__)

#See
print(p1.name)
print(p1.play_ball)

#increase
p1.age=19
print(p1.__dict__)
print(p1.age)

#modify
p1.age=20
print(p1.age)

#delete
del p1.age
print(p1.__dict__)

4.Scope of action

class MyData:
    pass
x = 50
y = 100
MyData.x=5
MyData.y=10
print(x,y)
print(MyData.x,MyData.y)
print(MyData.x+MyData.y)

  Like functions, classes also have the concept of scopes. Class can be regarded as the outermost function, and it is a scope. Instantiation automatically triggers the operation of the __init__ function and returns an instance. If you want to find the instance attribute, it is saved in the local scope of the __init__ function. Class and realityThe dictionary attributes of an example are their respective scopes. Therefore, a point is represented by a layer of action, and an instance is found first from its own scope, and can not find the dictionary of the class to the outer layer. In a class, the use of no point calls is called global variables.

Five. Static property, class method, static method

1.Static property

  Static attribute: the function attribute is encapsulated into the form of data attribute through the @property decorator. When it is called, it can not be seen outside, and can not be modified.

class Room:
    def __init__(self,name,owner,length,width,heigh):
        self.Name = name
        self.Owner = owner
        self.Length = length
        self.Width = width
        self.Heigh = heigh
    @property#Encapsulation logic
    def cal_area(self):
        return self.Length*self.Width

r1 = Room("303","dazui",10,8,3)
print(r1.cal_area)
# r1.cal_area = 10#Make a mistake

2.Class method

  Class method: through the @classmethod decorator, the class method can only access the data attributes of the class, and can not access the data attributes of the instance.

class Dog:
    name = "Jack"
    
    def __init__(self, name):
        self.name = name
        
    @classmethod
    def talk(self):
        print("%s is talking." % self.name)
dog = Dog("Tom")  # To instantiate a dog called Tom
dog.talk()#Jack is talking.

3.Static method

  Static method: the static method can not access the instance variable or class variable through the @staticmethod decorator. The only connection with the class is that the method needs to be called by the class name.

class Dog:
    name = "Jack"
    def __init__(self, name):
        self.name = name

    @staticmethod  # A method that belongs to a class but fails to access properties of classes or instances.
    def eat(self, food):
        print("%s is eating %s" % (self.name, food))
    @staticmethod
    def drink(name,water):
        print("%s is eating %s" % (name, water))

dog = Dog("Tom")# When eat becomes a static method, it will not automatically pass the instance itself as a parameter to self after it is invoked by instance.
# dog.eat("Apple")# TypeError: eat() missing 1 required positional argument: 'food'
dog.eat(dog, "Apple")# The right posture
dog.drink("Jack","Coco")# Used as an ordinary method, incoming location parameters
Dog.drink("Jerry", "Sprit")# Call directly through class names

Six, combination

  A combination is used in one class to another class, so that several classes can be spelled together. The combination is to do association and reduce duplicated code.

#Define a room
class Door:
    pass
class Window:
    pass
class Wall:
    pass

class Room:
    def __init__(self,name,door,window,wall):
        self.name = name
        self.door = Door()
        self.window = Window()
        self.wall = Wall()

Seven, the inheritance of the three features of object oriented programming

1.Class inheritance

  Inheritance is a way to create a new class. In Python, a new class can inherit from one or more parent classes, inheriting a parent class called single inheritance, and inheriting multiple parent classes as multiple inheritance. The parent class is also called the base class, and the subclass is also called the derived class.

  The subclass inherits all the properties of the parent class, but even if the name of the child class is the same as that of the parent class, the subclass will not overwrite the parent class.

class Parentclass1:
    pass
class Parentclass2:
    pass
class Subclass1(Parentclass1):#single inheritance
    pass
class Subclass2(Parentclass1,Parentclass2):#Multiple inheritance
    pass

 

2.The use of combination and class

  When there are significant differences between classes, and smaller classes can form larger classes, the combination is better; when there are a lot of the same functions between classes, these common functions are extracted as the base class, with inheritance.

  With inheritance, any small change also needs to redefine a class, which can easily cause an explosive growth of the class, producing a large pile of subtypes of subtypes. So there is a principle of “multipurpose combination less inheritance”.

3.Derivation, inheritance, and inheritance structure

  Derivation is a subclass that derives new attributes on the basis of inheriting the parent class. Unique in a subclass, not in the parent class; or a subclass that defines the same name as the parent class. Subclasses are also called derived classes.

  Inheritance is a way to inherit subclass attributes from the parent class.

  Inheritance structure is derived from multi generation, and continuous subclasses are related to ancestral classes.

4.Interface inheritance

  Inheritance has two meanings at the same time: (1) the method of inheriting the base class and making its own change or extension; (2) declaring that a subclass is compatible with a base class, defines an interface class, subclasses inherit the interface class, and implements the method defined in the interface.

  The first meaning of inheritance is not significant, and it can make the subclass and the base class have strong coupling. The second meaning is also called interface inheritance, which is very important.

  Interface inheritance is essentially a compatible interface, and external callers do not have to relate to specific details and only handle objects that implement a specific interface, which is called normalization in program design.

  Normalization enables high-level external users to process all interfaces compatible object sets without distinction.

import abc
class All_file(metaclass=abc.ABCMeta):
    @abc.abstractmethod#Defining interfaces, subclasses must implement this function, otherwise they will report errors.
    def read(self):
        pass
    @abc.abstractmethod
    def write(self):
        pass
class CDrom(All_file):
    def read(self):
        print("CDrom read")
    def write(self):
        print("CDrom write")
class Mem(All_file):#Due to the failure to implement the write function, the error will be reported
    def read(self):
        print("mem read")

 

5.Succession order

  PythonIf a class inherits multiple classes, then there are two ways to look for inheritance order: depth first and breadth first. The classic class will be searched by depth first, and the new class will be looked up according to breadth first.

class A:
    # def test(self):
    #     print("A")
    pass
class B(A):
    # def test(self):
    #     print("B")
    pass
class C(A):
    # def test(self):
    #     print("C")
    pass
class D(B):
    # def test(self):
    #     print("D")
    pass
class E(C):
    # def test(self):
    #     print("E")
    pass
class F(D,E):
    def test(self):
        print("F")
    # pass
f1 = F()
f1.test()#2.7 Depth first F--> D--> B--> A--> E--> C--> error reporting; 3.5 breadth first F--> D--> B--> E--> C--A--> newspaper.Wrong
print(F.__mro__)
print(F.mro() )

 

  For each class defined, Python accounts for a list of method parsing order (MRO), which is a simple linear sequence list of all the base classes.

  In order to achieve inheritance, Python looks up the base class from left to right in the MRO list. The construction of the MRO list is realized by a C3 linearization algorithm.

  All MRO lists follow three criteria: (1) subclasses will be checked before the parent class; (2) multiple parent classes are checked according to their order in the list; (3) if the next class has two choices, the first choice is preferred.

6.The method of calling the parent class in the subclass

  The subclass inherits the method of the parent class and wants to change the parent class based on the original base modification.

class Vehical:
    def __init__(self,name,speed,load,power):
        self.name = name
        self.speed = speed
        self.load = load
        self.power = power
    def run(self):
        print("Mahlzeit")
class Subway(Vehical):
    def __init__(self,name,speed,load,power,line):
        # Vehical.__init__(self,name,speed,load,power)
        # super().__init__(name,speed,load,power)
        super(Subway,self).__init__(name,speed,load,power)
        self.line = line
    def show_info(self):
        print(self.name,self.speed,self.load,self.power,self.line)
    def run(self):
        # Vehical.run(self)
        super().run()
        print("%s %s Mahlzeit" %(self.name,self.line))
line3=Subway("tianjin metro","80km/h","500","electricity",3)
line3.show_info()
line3.run()

 

Eight. The three major features of object oriented programming

1.polymorphic

  The object that is obtained by different class instantiation is called the same method, the execution logic is different, the polymorphism is the technique of calling method, it does not affect the internal design of the class, and the external invoking flexibility of the code can be increased.

class H2O:
    def __init__(self,name,temperature):
        self.name = name
        self.temperature = temperature
    def turn_shape(self):
        if self.temperature<=0:
            print("The current temperature is%s C and becomes%s" %(self.temperature,self.name))
        if self.temperature >0 and self.temperature<100:
            print("The current temperature is%s C and becomes%s" % (self.temperature, self.name))
        if self.temperature >= 100:
            print("The current temperature is%s C and becomes%s" % (self.temperature, self.name))
class Water(H2O):
    pass
class Ice(H2O):
    pass
class Steam(H2O):
    pass

w1 = Water("water",50)
i1 = Ice("ice",-30)
s1 = Steam("steam",5000)
def func(obj):
    obj.turn_shape()
func(w1)

 

Nine, the encapsulation of the three characteristics of object-oriented programming

1.What is encapsulation

  Encapsulation is to protect privacy, an abstraction of a specific object that is hidden from some parts and can not be seen outside the program, and its meaning is that other programs cannot call.

2.Two conventions

  (1)The names at the beginning of a single underline are both private.

  (2)The subclass cannot be overwritten when the property at the beginning of the double underline is inherited to the subclass.

3.usage

  In most cases, start with a single underline, when you know that the code will be designed to the subclass, and some of the internal properties should be hidden in the subclass, using a double underline.

4.Code

#Single line line
class People:
    _star = "earth"
    def __init__(self,id,name,age,salary):
        self.id = id
        self.name = name
        self.age = age
        self.salary = salary
    def get_id(self):
        pass
print(People._star)
p1 = People(112233,"Big mouth",24,0)
print(p1._star)

#Double underline
class People:
    __star="earth"
    def __init__(self,id,name,age,salary):
        self.id = id
        self.name = name
        self.age = age
        self.salary = salary
    def get_id(self):
        pass
p1 = People(112233,"Big mouth",24,0)
print(People.__dict__)
print(p1._People__star)

 

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *