New Python object-oriented ~ ~ ~ learning record

Posted by TexasMd91 on Tue, 01 Mar 2022 00:59:07 +0100

catalogue

1, Class definition and creation:

-Simple creation:

-Class properties:

2, Instance object

-Instance object method: class name ()

-Instance object method:_  init _ _ method

3, Method

-Example method

-Static method

-Class method

4, Class inheritance

-Succession:

-Method overrides in inheritance

-Reference parent class method

-Multiple inheritance of classes

-Direct (object) and object dict

5, Practice

 class DogCat(object):  # Naming rules for class names: big hump (capitalize the first letter of each word)
    pass

 

Learning record ~ ~ ~ section (learning ing ~)

1, Class definition and creation:

Definition: class (abstract concept): having the same characteristics (properties) and behaviors (Methods).

-Simple creation:

Simple creation:

  • Naming rules for class names: big hump (capitalize the first letter of each word)

  • class keyword creation

Simple creation of classes,

 class DogCat(object):  # Naming rules for class names: big hump (capitalize the first letter of each word)
    pass

-Class properties:

Class properties:

  • Class attribute assignment
 class Student(object):
    # Class properties
    class_name = "8 class"  
    student_num = 30

After a student class is created here, it is given two attributes: class name and number of students. And they are class attributes.

  • Access to class properties
     class Student(object):
        # Class properties
        class_name = "8 class"
        student_num = 30
    
    # Method 1   # Directly through: class name Class properties
    print(Student.student_num)
    
    # Method 2   # First instantiate the object through: instance object Property to find
    s = Student()
    print(s.student_num)
    
    

    The second method in the above code: it instantiates the object first, through the instance object Property, but there is no student in the instantiated object space_ With the attribute num, it will continue to look in the class space (or in the class it inherits).

  • Modification of class properties
class Student(object):
    # Class properties
    class_name = "8 class"
    student_num = 30
    name = "Earth dog"


# Modification of class attribute: class name Attribute name. If there is no such attribute, create a new attribute; If so, modify it
Student.name = "Silly cat"  # modify
Student.age = 100  # newly build

print(Student.name)
print(Student.age)

Visual results:

 

2, Instance object

The defined class can be used only after instantiation, that is, after using this class to create objects.

-Instance object method: class name ()

 class Student(object):
    # Class properties
    class_name = "8 class"
    student_num = 30
 
s = Student() # Instantiate object

-Instance object method:_  init _ _ method

When we need multiple instance objects, the first method will cause code redundancy, so there is__ init__ The role of the method.
Take an example:

class Student(object):
    # Class properties
    name = "Huazi"

    # method
    def __init__(self, name, age):  # Formal parameter, receiving the input of argument
        self.name = name  # For the parameters here, the front name can be customized, while the rear name cannot be changed, because it should be consistent with our new parameters, which is equivalent to the parameters passed in the function
        self.age = age

    def eat(self):
        print('Huazi is eating')


s1 = Student('Earth dog', '18')  # The number of arguments and parameters can be customized
s2 = Student('Silly cat', '19')
s3 = Student('Pig man', '20')

print(s1.name)
print(s2.name)
print(s3.name)

print(s1.age)

It should be noted here that Student() will only be assigned to variables such as s1 after instantiation, and it will be triggered automatically when Student() is instantiated__ init__ Method, and we can think that self is s1, because the following figure:

 

Here we print out the id values of self and s1 and find that they are the same ~ ~ ~ so self is s1 and self The attribute name is s1 Attribute name, self The attribute name is to create an instance attribute into s1 this instance space. Then there is the incoming and receiving of arguments and formal parameters, which is similar to the arguments and formal parameters of functions.

  • Attribute assignment of instance object: instance object Attribute name

 

class Student(object):
    # Class properties
    class_name = "8 class"
    student_num = 30
    name = "Earth dog"


s = Student()
s.name = 'Huazi'
s.age = 18

print(s.name)  # When searching the name attribute, it is found that both class space and instance space have the name attribute,
# However, instance objects will be found in their own space first

 

So there will be:

  • Instance object The search order of attribute name is: it first finds it in its own instance space, if not; Then go to class space to find, if not; Then go to the class inherited by this class; If none, report an error~~~~~~~
  • Object invokes properties and methods through a period character: object Properties / methods
    code:
class Student(object):
    # Class properties
    name = "Huazi"

    def eat(self):
        print('Huazi is eating')

    def sleep(self):
        print('Huazi wants to sleep')


s = Student() 
print(s.name)  # Object call properties
s.eat()  # Call method

 

 

3, Method

-Example method

A method with self is an instance method, but the name of self is not the same. It can be other values, but the specification is used to self,
self represents the current object

Self is not a keyword. In fact, it can be any identifier. In order to express that it represents the current object itself, we are used to using self
When calling the instance function, self does not need to pass parameters manually, and the system will automatically pass the current object
Which object calls the method, and the self in the method refers to who.
Instance method call:
code:
 

class Student(object):
    # Class properties
    class_num = 30
    class_name = '8 class'

    # method
    def __init__(self, name, course):
        self.name = name
        self.course = course

    def listen(self):
        print('%s Listening%s course' % (self.name, self.course))  # name and course in self

    def homework(self):
        print('%s Writing%s Homework class' % (self.name, self.course))


s1 = Student('Huazi', 'python')  # Argument input
s1.listen()

s2 = Student('I', 'python')
s2.homework()

In the above code: s1 Listen (), which calls the method, the interpreter will pass s1 as an argument to the first formal parameter (self) of the method

-Static method

code:

class Sum(object):

    @staticmethod
    def add(x, y):   # There is no self parameter here
        return x + y


# Instance object calls static method:
s = Sum()
print(s.add(2, 6))

# Class object calls static methods:
print(Sum.add(6, 6))

-Class method

code:

class Sum(object):
    # Class properties
    num = 30

    @classmethod
    def add_num(cls):  # After adding @ classmethod here, the interpreter will automatically add the cls parameter.
        print(id(Sum), id(cls))
        cls.num += 1


Sum.add_num()
print(Sum.num)

 

It is found that the address of the parameter cls is the same as that of the Sum class. So cls is the current class object. The Sum class object acts as the receiver of cls.

4, Class inheritance

-Succession:

Inheritance: it is a mechanism for subclasses to reuse the properties and methods of their parent classes. In Python, a new class can inherit one or more parent classes. Note: object is the root class of all classes in Python.
Single inheritance: the inheritance of a subclass is a parent class, which is called single inheritance.
Multiple inheritance: a subclass can have multiple parent classes and all the properties and methods of the parent class.

Parent class: also known as base class or superclass
New class: called derived class or subclass
code:
Simple example:

 class Animal(object):
    def eat(self):
        print('eat')

    def sleep(self):
        print('sleep')


class Dog(Animal):  # Inherit Animal parent class
    def bark(self):
        print('Barking')


class Cat(Animal):
    def climetree(self):
        print('climb up a tree')


s1 = Dog()
s2 = Cat()
s1.eat()
s2.sleep()

If a subclass does not have attributes, you can find them in its inherited parent class.

-Method overrides in inheritance

code:

class Animal(object):
    def eat(self):
        print('eat')

    def sleep(self):
        print('sleep')


class Dog(Animal):  # Inherit Animal parent class
    def bark(self):
        print('Barking')

    def sleep(self):
        print('Sleep sleep.....')  # Although it inherits the sleep of the parent class, if the child class writes a sleep method, it will override it, but it will not affect the parent class


class Cat(Animal):
    def climetree(self):
        print('climb up a tree')


s1 = Dog()
s1.sleep()

s2 = Cat()
s2.sleep()

 

-Reference parent class method

  • Example 1
 class Animal(object):

    def __init__(self):
        self.parent = 'I'm a parent'
        print(id(self))
        print('Parent class')

    def sleep(self):
        print('I'm a parent')


class Dog(Animal):  # Inherit Animal parent class

    def sleep(self):
        super(Dog, self).sleep()  # super will first find the parent class of Dog (that is, Animal class), and then convert the object of Dog class (s) to Animal class object (self), because their id values are the same
        print('I'm a subclass of sleep.....')
        print(self.parent) # The parent attribute of the parent class was found


d = Dog()  # Don't forget, it will find__ init__ method
d.sleep()
print(id(d))

Note: super will first find the parent class of Dog (i.e. Animal class), and then convert the object of Dog class (s) to the object of Animal class (self), because their id values are the same

  • Example 2:
class Parent(object):
    def __init__(self):
        self.parent = 'I'm a parent'
        print(id(self))
        print('Parent class')

    def bar(self):
        print("I'm a parent bar")


class Child(Parent):
    def __init__(self):
        # super(Child,self) first finds the Parent class of Child (i.e. class Parent), and then converts the object of class Child (s) into the object of class Parent (self). Their id values are the same.
        super().__init__()  # super(Child, self).__init__()
        print('Subclass')

    def bar(self):
        super().bar()  # super().bar(message)
        print('I'm a subclass bar')
        print(self.parent) # Child's object (s) has been converted to a Parent like object (self)


s = Child()  # Instantiate a Child object
s.bar()  # Call bar method of s
print(id(s))

 

super().init() # can also be written as: Super (child, self) init() .

-Multiple inheritance of classes

code:

class Animal(object):
    def eat(self):
        print('eat')


class Fly(object):
    def fly(self):
        print('fly')


class Dog(object):
    pass


class BigBird(Animal, Dog, Fly):
    pass


class LittleBird(Fly, Animal):
    pass

b = BigBird()
b.fly()

c = LittleBird()
c.fly()

 

For the inheritance of multiple classes, the subclass inheritance is sequential: from left to right

Then:

  • type() method: in addition to judging the type of string, it can also judge which class the instance object belongs to.
print(type(b))
print(type(c))

  • isinstance() method: judge whether an object is an instance of a class. If it is true, it will be true. If it is true, the inherited parent class will also be true
    code:

 

print(isinstance(b, BigBird))
print(isinstance(b, Fly))
print(isinstance(b, LittleBird))

 

-Direct (object) and object dict

  • Direct (object) and object dir() is equivalent. The dir() method can get all the properties and methods of the object and return them as a list.

print(dir(b))
print(c.__dir__())  

 

They return in different order, but the content is the same~~~~

  • object__dict__ It can get the custom properties of the object and return them in the form of a dictionary.
    code:
print(c.__dict__)

Note: in direct (object), it is equivalent to just taking out the key and putting it in the object__dict__ In, it takes out both key and value.

5, Practice

 

Topics: Python