Today we’re looking at day two of object-oriented

1. Basic syntax for inheritance

Inheritance: The relationship between classes described. Basic syntax: class class B(class A): pass Called class B inherits class A Features: Objects of class B can use properties and methods of class A Advantages: code reuse. Repeating the same code doesn't have to be written more than once. Noun: class A: superclass base class B: subclass derived class


# 1. The definition is an animal
class Animal(object) :
    # 2. Write the play method in the naimal class to output happy play
    def play(self) :
        print('Happy play..... ')


# 3. Define Dog as a descendant of animal
class Dog(Animal) :
    pass


# 4. Create a dog object. Call the method of the parent class
dog = Dog()
dog.play()
Copy the code

2. Single inheritance and multiple inheritance

 # 1. It's an animal
 class Animal(object) :  For Animal and object classes, single inheritance
      # 2. Write the play method in animal class, output happy play...
      def play(self) :
         print('Happy play... ')
 
 
 # 3. Define Dog as a descendant of animal
 class Dog(Animal) :  # Dog -- > animal == object
      def bark(self) :
          print('Woof woof woof.... ')
     
# define class XTQ, which inherits dog
In multi-level inheritance, subclasses can use methods and attributes from all classes in the inheritance chain
class XTQ(Dog) :
      pass
    
Copy the code

3. A subclass overrides a method of the same name in its parent class

# 1. Define the Dog class and write the bark method to output a bark
class Dog(object) :
    def bark(self) :
        print('Bark.... ')


# 2. Define the XTQ class that inherits the Dog class and overrides the bark method in the parent class. Output cry
class XTQ(Dog) :
    def bark(self) :
        print('cry out')


# create Dog object
dog = Dog()
dog.bark()

Create an XTQ object
xtq = XTQ()
xtq.bark()
Copy the code

4. A subclass calls a method of the same name as its parent

# 1. Define the Dog class and write the bark method to output a bark
class Dog(object) :
    def bark(self) :
        print('Woof woof woof.... ')


# 2. Define the XTQ class that inherits the Dog class. Overrides the bark method in the parent class to produce a bark


class XTQ(Dog) :
    def bark(self) :
        print('......... ')

    def see_host(self) :
        print('I see my master.', end=' ')
        # self.bark()
        You want to call a method of the same name as the parent in a subclass
        Method 1: The parent class name. Method name (self, other arguments) through the instance object. Method name () calls the method without passing the argument value to self,
        The Python interpreter automatically passes the object as an argument value to the self parameter, if by class name. Method () is called, the Python interpreter is called
        The argument value will not be passed automatically. The argument value will be passed manually to the self parameter
        Dog.bark(self)

        Super (class A, self). The method name (argument) will call the method that is the parent of class A
        super(XTQ, self).bark()  Call the bark method from the parent of XTQ

        # method 3 is short for method 2, super(). Method name (parameter name) == super(current class, self). Method name ()
        super().bark()


Create an XTQ object
xtq = XTQ()
xtq.see_host()
Copy the code

Init in inheritance

# 1. Define Dog class
class Dog(object) :

    def __init__(self, name) :
        # add attribute
        self.age = 0
        self.name = name

    def __str__(self) :
        return F 'is named:{self.name}'


# 2. Define class XTQ to inherit from class Dog
class XTQ(Dog) :
    # Subclasses override the __init__ method of the parent class. By default, the parent class's init method is no longer called, so you need to manually call the parent class's init method
    def __init__(self, name, color) :
        super().__init__(name)
        self.color = color

    def __str__(self) :
        return F 'is named:{self.name}, the age of{self.age}, the color is:{self.color}'


# 3. Create an XTQ object
xtq = XTQ('black'.'red')
print(xtq)
Copy the code

6. Multiple inheritance

# 1. Define the Dog class, and define the bark and eat methods
class Dog(object) :
    def bark(self) :
        print('Woof woof woof.... ')

    def eat(self) :
        print('Bone gnawing.... ')


# 2. Define the God class, and define the play and eat methods
class God(object) :
    def play(self) :
        print('Float in the clouds for a while.... ')

    def eat(self) :
        print('Eat flat peach Dan..... ')


# 3. Define the XTQ class that inherits the Dog and God classes
# class XTQ(Dog, Dod): The XTQ class has two parent classes. This inheritance relationship is called multiple inheritance. Xtq-class objects can call properties and methods in both parent classes
class XTQ(God, Dog) :  # XTQ class has two parent classes. This inheritance relationship is called multiple inheritance. XTQ class objects can call properties and methods in both parent classes
    pass


# 4. Create an XTQ object
xtq = XTQ()
xtq.bark()  # call the method in Dog's parent class
Copy the code

7. Private permission

Access control, where private permissions can be used and manipulated:

  • Definition: Methods and properties become private when preceded by two underscores
  1. You cannot access and use objects directly outside the class, only inside the class
  2. Cannot be inherited by subclasses
Private method: A method preceded by two __ is private. This method is private and cannot be accessed from outside the class. It is used as an internal method and cannot be called from outside the class.


class Dog(object) :
    def born(self) :
        """ The way to give birth to a puppy, give birth to a puppy and rest for 30 days. """
        print('Gave birth to a puppy')
        self.__sleep()

    def __sleep(self) :
        print('Rest for 30 days')


dog = Dog()

dog.born()

Copy the code

8. Class attribute

Object (instance object): created by a class defined by class, that is, by class instantiation, also called an instance, instance object Instance object defined properties are called instance properties. Attributes defined by an instance object (self) are instance attributes. Instance attributes: There is a copy of each instance object and the value may be different. Class (class object): Defined by class. 2. Class objects can store some attribute information, called class attributes. The definition of class attributes: Inside a class, variables defined outside a method are class attributes. Assuming the property is an instance property, check whether the property value is the same for different instance objects and needs to change at the same time. If it is, you can define it as a class property if it is not, you can define it as an instance property """


class Dog(object) :
    # define class attributes, class names
    class_name = 'dogs'

    def __init__(self, name, age) :
        All instance attributes are defined
        self.name = name
        self.age = age


# create Dog object
dog = Dog('rhubarb'.2)
print(dog.__dict__)

Dict Looks at the properties that a class object has
print(Dog.class_name)

Alter class attribute class name. Class attribute = attribute value
Dog.class_name = 'Dog class'

print(Dog.class_name)
Note: If there is no class attribute with the same name as the instance attribute. Side can use instance objects to access the values of class attributes
If there is a duplicate name, use the instance attribute to access the instance object, not the class attribute
print(dog.class_name)

Copy the code

9. Class methods

"" Instance method: a method defined by default in a class, that is, an instance method. The first argument, self, represents the instance object class method: A method decorated with @classmethod is called a classmethod, and the first argument is CLS, which represents the class object itself when is it defined as an instance method or a classmethod? 1. If an instance attribute is used in a method, that method must be defined as an instance method. Prerequisite: You do not need to use instance attributes. To use class attributes, you can define this method as a class method.


class Dog(object) :
    class_name = 'dogs'

    def __init__(self, name, age) :
        self.name = name
        self.age = age

    def play(self) :  # instance method
        print(F the dog"{self.name}In happy play....")

    # def get_class_name(self):
    # return Dog.class_name

    @classmethod
    def get_class_name(cls) :
        return cls.class_name


dog = Dog('rhubarb'.2)
dog.play()
print(dog.get_class_name())  Class method ()

Class method ()
print(Dog.get_class_name())

Copy the code

10. Static methods

Instance method: a method defined in a class by default, which is the instance method. The first argument is self, which represents the instance object classmethod. The method decorated with @classmethod is called the classmethod. A method decorated with @staticmethod is called a staticmethod. It has no special parameters. It can have, but can not be defined as an instance method, a class method, or a staticmethod. 1. If an instance attribute is used in a method, that method must be defined as an instance method. Prerequisite: You do not need to use instance attributes. If you want to use a class attribute, you can define this method as a class method. 3.


class Dog(object) :
    class_name = 'dogs'

    def __init__(self, name, age) :
        self.name = name
        self.age = age

    def play(self) :  # instance method
        print(F the dog '{self.name}At happy play.... ')

    @staticmethod  Define static methods
    def show_info() :
        print('This is a Dog class')


dog = Dog('rhubarb'.2)
dog.play()
# object. Method name ()
dog.show_info()
Class name. Method name ()
Dog.show_info()
Copy the code

11. Polymorphism

Where you need to use a parent class object, you can pass in a subclass object and get a different result. Subclasses inherit from the parent class. 2. Subclasses override the same methods in the parent class. 3. Call a method in a method whose subclass has the same name as its parent class.


# 1. Define Dog class
class Dog(object) :
    def __init__(self, name) :
        self.name = name

    def play(self) :
        print(F the dog '{self.name}In the play... ')


# 2. Define crouching dogs and inherit the Dog category
class XTQ(Dog) :
    # 3. Override the Play method
    def play(self) :
        print(f'{self.name}Chasing clouds in the sky.... ')


# 4. Define a common approach
def play_with_dog(obj_dog) :
    obj_dog.play()


# create Dog object
dog = Dog('rhubarb')
play_with_dog(dog)


Create an object of class XTQ
xtq = XTQ('black')
play_with_dog(xtq)

Copy the code