"python" Object-Oriented Introduction (with diagram) in detail

Article catalog

object-oriented

Defining classes

Syntax:
class name:
Members of class
Members in a class: instance properties, instance methods, class properties, class methods, static methods, etc
The following will explain all the members of the class separately. The code is independent. For the convenience of understanding!

Define a class and create a class instance

# Define a class, using the class keyword
class Student:
    pass # Not assigned temporarily

#Create object of class
stu1 = Student() # Create an instance of the Student class
stu2 = Student()
print(stu1,'Custom type type: ',type(stu1))
print(stu2,'Custom type type: ',type(stu2))

# Test, compare type
a = 666
print(a,'default type:',type(a))
c = 'six six six'
print(c,'default type:',type(c))
print('*' * 59)

Binding instance properties for objects

# Define a class, using the class keyword
class Student:
    pass # Not assigned temporarily

#Create object of class
stu1 = Student() # Create an instance of the Student class
stu2 = Student()
print(stu1,'Custom type type: ',type(stu1))
print(stu2,'Custom type type: ',type(stu2))

# Binding properties for objects (Note: you need to create an instance of the class first)
stu1.name = 'ccx'
stu1.age = 22
stu2.name = 'xgq'
stu2.age = 23
stu2.sex = 'woman'
print('stu1 Parameters of:',stu1.name,stu1.age) #Print stu1 parameters
print('stu2 Parameters of:',stu2.name,stu2.sex,stu2.age) # Print stu2 parameters

Creating and using instance methods

  • The following method is the default method of not passing parameters
# Define a class, using the class keyword
class Student:
    #pass # Not assigned temporarily
    # Create instance method: method with self as the first parameter (self generated automatically)
    def say_hi(self):  # self represents an instance of the current class, similar to this in java
        print('Hi ' + self.name) # Pass in the name parameter.

#Create object of class
stu1 = Student() # Create an instance of the Student class
stu2 = Student()
#print(stu1, 'custom type:', type(stu1))
#print(stu2, 'custom type:', type(stu2))

# Binding properties for objects (Note: you need to create an instance of the class first)
stu1.name = 'ccx'
stu1.age = 22
stu2.name = 'xgq'
stu2.age = 23
stu2.sex = 'woman'
# print('stu1 Parameters of:',stu1.name,stu1.age) #Print stu1 parameters
# print('stu2 Parameters of:',stu2.name,stu2.sex,stu2.age) # Print stu2 parameters

#Access instance method
stu1.say_hi() # The method is called without passing self, and the object is passed in automatically as self when called by the parser
stu2.say_hi()

  • Let's talk about the method of parameter passing
# Define a class, using the class keyword
class Student:
    #pass # Not assigned temporarily
    # Create instance method: method with self as the first parameter (self generated automatically)
    def say_hi(self):  # self represents an instance of the current class, similar to this in java
        print('Hi ' + self.name) # Pass in the name parameter.
    # Create a method to pass parameters
    def say_hello(self,username='The default is hero'): #Default values defined
        print('hello ',username)

#Create object of class
stu1 = Student() # Create an instance of the Student class
stu2 = Student()

# Binding properties for objects (Note: you need to create an instance of the class first)
stu1.name = 'ccx'
stu2.name = 'xgq'

# Call methods that do not need parameters
stu1.say_hi()
stu2.say_hi()
#Call the method of parameter passing
stu1.say_hello() # No error will be reported without reference
stu2.say_hello('Cui') # Biography of ginseng

Class properties

# Define a class using the class keyword
class Student:
    # Class attribute: the attribute defined directly in the class, which can be accessed through the class or instance object
    boy = 'good enveving '

stu1 = Student()  # Create a class object
stu2 = Student()

# Access class properties
print(Student.boy)
stu1.boy = 'Good evening' #stu1 adds an instance property and does not change the value of boy in the class property
print(stu1.boy)
print(stu2.boy) # If the current instance does not have a boy attribute, the class attribute boy will be looked up

Class method

# Define a class using the class keyword
class Student:
    # Class attribute: the attribute defined directly in the class, which can be accessed through the class or instance object
    boy = 'good enveving '

    #Class method: use the method decorated with @ classmethod, with cls as the first parameter
    @classmethod
    def show(cls, msg):  # cls is generated by default and represents the current class. msg is the custom parameter value
        print(msg,cls.boy)

stu1 = Student()  # Create a class object
stu2 = Student()

# Access class properties
# print(Student.boy)
# stu1.boy = 'Good evening' #stu1 adds an instance property and does not change the value of boy in the class property
# print(stu1.boy)
# print(stu2.boy) # If the current instance does not have a boy attribute, the class attribute boy will be looked up

#Call class method
# Called by class
Student.show('ccx') #The method does not need to pass cls, but msg is defined, so a parameter needs to be passed in
# Call through object
stu1.show('xgq')

Static class method

# Define a class using the class keyword
class Student:
    # Class attribute: the attribute defined directly in the class, which can be accessed through the class or instance object
    boy = 'good enveving '

    #Class method: use the method decorated with @ classmethod, with cls as the first parameter
    @classmethod
    def show(cls, msg):  # cls is generated by default and represents the current class. msg is the custom parameter value
        print(msg,cls.boy)

    # Static method: the method decorated with @ static method does not have any required parameters. cls is not required as the first parameter
    @staticmethod
    def show2(msg):  # msg is OK
        print(msg,Student.boy) #Because there is no cls representation class, to call the properties in the class, you can directly use the class name. Property

stu1 = Student()  # Create a class object
stu2 = Student()

#Call class method
# Called by class
Student.show('ccx') #The method does not need to pass cls, but msg is defined, so a parameter needs to be passed in
# Call through object
stu1.show('xgq')
print('*' * 50)
# Call static class method
Student.show2('Cui Chongxin') # Called by class
stu1.show2('xgq') # Call through object

Construction method

# Below__ It's two underscores
__int__() : Constructor, called automatically when an object is created
class Student:
    #Constructor (function), overload not supported
    def __init__(self,name,age): #self is auto generated (the current class), and name and age are the values to be initialized
        print('Create objects, execute construction methods...')
        self.newname = name # Initialization value, must be initialized!!!!!
        self.newage = age

    # Instance method
    def show(self):
        print(self.newname,self.newage)
        print('mr %s ,Age %d' % (self.newname,self.newage))

# Call constructor
stu1 = Student('ccx',22) #Create the object and pass in 2 Parameters
print(stu1.newname,stu1.newage) #output
print('*' * 50)

#Call instance method
stu1.show()

encapsulation

Encapsulation: hide some properties in the object that you don't want to be accessed externally to ensure data security.

General definition method: lack of concealment and data insecurity

class Student:
    pass

stu1 = Student()
stu1.num = 50
print(stu1.num)

Encapsulation method: no data can be seen outside, more secure

class Student:
    # Define private properties
    __num = 50  # Starts with two underscores, indicating the hidden properties of the object, which can only be accessed inside the class

    # Provide getter/setter methods
    def get_num(self):
        return self.__num  # Returns the value of the class as defined__ num value

    # Can be changed__ Value of num
    def set_num(self, num):
        # For example, you only want to enter a value between 1-100, otherwise it is the default value
        if 0 < num < 101:
            self.__num = num  # num is the parameter passed in
            return self.__num
        else:
            self.__num = 50
            return self.__num


stu1 = Student()  # create object

# Call wrapped value
# print((stu1.__num)) # Private property cannot be accessed outside the external class
print('Normal call:',stu1.get_num())  # Call the value of the normal return class
print('Input 66:',stu1.set_num(66))
print('Input 666:',stu1.set_num(666))

inherit

Inheritance: enabling one class to get properties and methods from other classes
Parent class: in fact, it is a common class name(object). Objects in the parent class can be omitted, so class name can be used directly
Child class inherits parent class: class name (parent class name)

Define the parent class, and the child class inherits the use of the parent class

#Define a Person class, parent class (super class, base class)
class Person:
    def __init__(self,name): # Define private class
        self.name = name
    def run(self):#Define a class function
        print('person:'+ self.name+'Running')

class Student(Person): #Inherited from Person
    def __init__(self,name,set,age):# Define private class
        #Call the constructor of the parent class
       # Person.__init__(name) # Method 1: directly specify the construction method of parent class
        super().__init__(name)# Method 2: use super(), which is recommended
        # If the constructor in your own class does not exist in the parent class, you can define it directly
        self.set = set
        self.age = age
    def study(self): #Define a class function
        print('stadent:' + self.name + 'I am learning....')
    def show(self):#Define a class function
        print('name:%s , set:%s,age:%s'%(self.name,self.set,self.age))
    #You can customize n class functions...

stu = Student('ccx','man',22)
stu.run() #Because it inherits the parent class, you can also call the parent class function directly
stu.study()
stu.show()

Subclass override parent

In fact, you can overwrite the content of the method in the parent class by re editing the same method name as the parent class in the child class. super(). The parent class method name () is to call the content of the parent class method. If you do not want this line, all the content in the parent class method will be invalid. Then define the new content in the subclass method. Printing the content displayed by this method is the content of the subclass method.

#Define a Person class, parent class (super class, base class)
class Person:
    def __init__(self,name): # Define private class
        self.name = name
    def run(self):#Define a class function
        print('person:'+ self.name+'Running')

class Student(Person): #Inherited from Person
    def __init__(self,name,set,age):# Define private class
        #Call the constructor of the parent class
       # Person.__init__(name) # Method 1: directly specify the construction method of parent class
        super().__init__(name)# Method 2: use super(), which is recommended
        # If the constructor in your own class does not exist in the parent class, you can define it directly
        self.set = set
        self.age = age
    def study(self): #Define a class function
        print('stadent:' + self.name + 'I am learning....')
    def show(self):#Define a class function
        print('name:%s , set:%s,age:%s'%(self.name,self.set,self.age))
    #You can customize n class functions...
    # Override method of parent class
    def run(self):
        #super().run() #Call the method of the parent class. If you do not want this line, the content of this method in the parent class will not be output
        print('new person :'+ self.name+'Running') #New definition method content

stu = Student('ccx','man',22)
stu.run() #Because it inherits the parent class, you can also call the parent class function directly
stu.study()
stu.show()

Common condition judgment

#Define a Person class, parent class (super class, base class)
class Person:
    def __init__(self,name): # Define private class
        self.name = name
    def run(self):#Define a class function
        print('person:'+ self.name+'Running')

class Student(Person): #Inherited from Person
    def __init__(self,name,set,age):# Define private class
        #Call the constructor of the parent class
       # Person.__init__(name) # Method 1: directly specify the construction method of parent class
        super().__init__(name)# Method 2: use super(), which is recommended
        # If the constructor in your own class does not exist in the parent class, you can define it directly
        self.set = set
        self.age = age
    def study(self): #Define a class function
        print('stadent:' + self.name + 'I am learning....')
    def show(self):#Define a class function
        print('name:%s , set:%s,age:%s'%(self.name,self.set,self.age))
    #You can customize n class functions...
    # Override method of parent class
    def run(self):
        #super().run() #Call the method of the parent class. If you do not want this line, the content of this method in the parent class will not be output
        print('new person :'+ self.name+'Running') #New definition method content

stu = Student('ccx','man',22)
stu.run() #Because it inherits the parent class, you can also call the parent class function directly
stu.study()
stu.show()

#Determine whether an object specifies an instance of a class, that is, determine the type of the object
print(isinstance(stu,Student))
print(isinstance(stu,Person))

# Determine whether a class is a subclass of a specified class
print(isinstance(Student,Person))
print(isinstance(Person,object))

# Object class is the root class of all classes. By default, all classes inherit from object
print(stu.__doc__) # Output the content of the comment at the beginning of the file ("" "" ""). If there is no comment, it is None
print(stu.__dict__) # Print stu values as dictionaries

Multiple inheritance

Multiple inheritance: as the name implies, a class can inherit multiple parent classes, and multiple parent classes can be separated by commas.
Note: multi inheritance is not recommended, because if the methods in parent class A and parent class B are the same, there will be problems of overriding or loading order.

# Define a parent class B
class A:
    def a(self):
        print('a')
# Define a parent class B
class B:
    def b(self):
        print('b')
# Define a class and inherit multiple parent classes, separated by commas (inheritance of multiple classes is not supported in java)
class C(A,B):
    def c(self):
        print('c')

stu = C()
stu.a()
stu.b()
stu.c()

# Class has a special property__ bases__  Can be used to get all the parent classes of the current class
print(C.__bases__)

polymorphic

Polymorphism: can be displayed in many different forms!

class Animal: #Define an animal class
    def __init__(self,name):
        self.name = name

    def cry(self):
        print('Animals are barking....')

class Dog(Animal) : # Define a dog like class and inherit the animal class
    def __init__(self,name,age):
        super().__init__(name)
        self.age = age
    def cry(self):
        print('The dog is barking... Wang Wang Wang')

class Cat(Animal) : # Define a class hair and inherit the animal class
    def __init__(self,name,sex):
        super().__init__(name)
        self.sex = sex
    def cry(self):
        print('The cat is barking... Whoa, whoa, whoa')

#An object can be presented in different forms, that is, polymorphism
def play(name):  # Note that this calls the above class as a function's method
    print(name.name) #Return by name, only one name returns the memory address
    name.cry() # Return the content of the cry method in the class

# create object
dog = Dog('chinese rhubarb',2)
cat = Cat('Meina ','common')
play(dog)
play(cat)

Magic Methods

What is Python magic method?

Magic method is just as magical as its name. It can always provide you with a way to make your idea come true when you need it. Magic methods refer to the methods already included in Python and surrounded by double underscores. These methods will be called automatically when performing specific operations. They are the crystallization of Python's object-oriented wisdom. It is very important for beginners to master Python's magic methods.

Why use Python magic methods?

Using Python magic method can make Python more free. When there is no need to rewrite the magic method, it can also take effect under the specified default conditions. When there is a need to rewrite, users can also rewrite some methods according to their own needs to achieve their expectations. As we all know, Python is the basic magic method to support the object-oriented language python, which makes Python do better in the aspect of object-oriented.

Some grammar of magic method

Basic magic methods (more commonly used)

#Below__ It's all two underscores
 Wei new__(cls [,...]) is the first method called by the instantiated object. It only takes cls parameters and passes other parameters to__ init__.  __ new__ It is rarely used, but there are also scenarios (singleton patterns) for it, especially when a class inherits from a type that doesn't change often, such as a tuple or string.
Wei init__(self [,...]) constructor, called when class is initialized
 Wei del__(self) destructor, called when the instantiated object is completely destroyed (all pointers of the instantiated object are destroyed)
Wei call__(self[, args...]) allows an instance of a class to be called like a function: x(a, b) calls X__ call__ (a, b)
Wei len__(self) defines the behavior when called by len()__ repr__(self) defines the behavior when called by repr()
Wei str__(self) defines the behavior when called by str()__ bytes__(self) defines the behavior when called by bytes()
Wei hash__(self) defines the behavior when called by hash()
Wei bool__(self) defines the behavior when called by bool(), which should return True or False
 Wei format__(self, format_spec) defines the behavior when called by format()

Property related methods

#Below__ Both underscores
 Wei getattr__(self, name) defines the behavior when a user attempts to get a nonexistent property
 Wei getattribute__(self, name) defines the behavior of the class when its properties are accessed
 Wei setattr__(self, name, value) defines the behavior when a property is set
 Wei delattr__(self, name) defines the behavior when an attribute is deleted
 Wei dir__(self) defines the behavior when dir() is called
 Wei get__(self, instance, owner) defines the behavior when the value of the descriptor is obtained
 Wei set__(self, instance, value) defines the behavior of a descriptor when its value is changed
 Wei delete__(self, instance) defines the behavior when the descriptor value is deleted

Comparison operator

#Below__ Both underscores
 Wei lt__(self, other) defines the behavior of less than sign: x < y calls X__ lt__ (y)
Wei le__(self, other) defines the behavior less than or equal to the sign: x < = y calls X__ le__ (y)
Wei eq__(self, other) defines the behavior of equal sign: x == y calls X__ eq__ (y)
Wei ne__(self, other) defines the behavior of unequal sign: X! = y calls X__ ne__ (y)
Wei gt__(self, other) defines the behavior of the greater than sign: x > y calls X__ gt__ (y)
Wei ge__(self, other) defines the behavior greater than or equal to sign: x > = y calls X__ ge__ (y)

Type conversion

#Below__ Both underscores
 Wei complex__(self) defines the behavior when called by complex() (needs to return the appropriate value)
Wei int__(self) defines the behavior when called by int() (needs to return the appropriate value)
Wei float__(self) defines the behavior when called by float() (needs to return the appropriate value)__ round__(self[, n]) defines the behavior when called by round() (need to return the appropriate value)

Container type (generally used to operate container class)

#Below__ Both underscores
 Wei len__(self) defines the behavior when called by len() (generally returns the length of the container class)
Wei getitem__(self, key) defines the behavior of getting the specified element in the container, which is equivalent to self[key]
Wei setitem__(self, key, value) defines the behavior of setting the specified element in the container, equivalent to self[key] = value
 Wei delitem__(self, key) defines the behavior of deleting the specified element in the container, which is equivalent to del self[key]
Wei iter__(self) defines the behavior of elements in an iteration container
 Wei reversed__(self) defines the behavior when called by reversed()
Wei contains__(self, item) defines the behavior when using the member test operator (in or not in)

characteristic:
1 starts with double underscores and ends with double underscores;
2 does not need to be called manually and will be executed automatically at a specific time.

  • Feature display
# Define a class
class Person(object) : # Object can not be used. All parent classes inherit object by default
    def __init__(self,name,age):
        print('__init__')
        self.name = name
        self.age = age


p1 = Person('Cui Chongxin',22)
print(p1) 

  • Function use (partial)
    Only part of the functions are shown here. For details, please refer to the above syntax. The usage is the same.
# Define a class
class Person(object) : # Object can not be used. All parent classes inherit object by default
    def __init__(self,name,age):
        print('__init__')
        self.name = name
        self.age = age
    # Called when converting an object to a string, similar to toString() in java
    def __str__(self): # If not, the memory address is returned
        return 'Person [name=%s,age=%d]' % (self.name,self.age)
    # Called when the object uses the len() function
    def __len__(self):
            return len(self.name)
    # Called when the object uses the repr() function
    def __repr__(self):
        return 'hello person'
p1 = Person('Cui Chongxin',22)
print(p1)
print(len(p1))
print(repr(p1))

Keywords: Python Attribute Java less

Added by CompuWorld on Tue, 23 Jun 2020 08:48:35 +0300