Process oriented and object-oriented
Process oriented |
|
object-oriented |
|
Class, object
Class: having a set of the same or phase A series of objects with characteristics (attributes) and behaviors (Methods). That is, a template, in which multiple functions can be included, and some functions can be realized in the functions.
Real world | Computer world |
behavior | method |
features | attribute |
Object: it is a real thing. The instantiation (visualization) of a class is based on the instance created by the template. The functions in the class can be executed through the instance object.
- Class is the abstraction of object, and object is the instantiation of class
- Class is equivalent to a drawing for manufacturing a car, and the car manufactured by the drawing is equivalent to an object
- Class composition structure: class name, class properties, and class methods
Define classes and objects
- Instance method: within the class, you can define an instance method using the def keyword. The first parameter is self
- Different from the general function definition, the class method must contain the parameter self (it's a keyword, it doesn't matter what it is, but it must have), For example, eat and run in class Person
- Methods of a class are owned by instances of the class
- Class attribute: the attribute inside the class and outside the method
- Class attributes are most common attributes, such as cat hair. However, there may be special parts and attributes that are different. For example, for hairless cats, class attributes cannot be used and instance attributes are required
- Instance attribute: the attribute referenced by [variable name similar to self. Variable name] defined inside the method is called instance attribute
- If there is an instance method, there will be an instance attribute. The instance attribute belongs to the instance method [_init_ function]
class Person: #Class name -- initial capital is recommended ''' Attribute of class: corresponding to human characteristics ''' name='Xiao Ming' #Class properties age=20 #Class properties ''' Class method [instance method]: the behavior of the corresponding person ''' def __init__(self): self.height=187 #height is an instance attribute. Do not use the same name as the class attribute pass def eat(self): #behavior print("A big meal") pass def run(self): print("Run fast") #Example method pass xm=Person() #Create an object: Xiao Ming xm.eat() # Call instance method (behavior of class) xm.run() print('{}What is your age{},Height is{}'.format(xm.name,xm.age,xm.height)) #Access the properties of the class
Magic method:__ init__ method
__ init__ Method is an initialization method. It is called automatically when instantiating an object to complete some initialization settings.
class People(): #Define a simple class without defining class properties def __init__(self,name,sex,age): #The parameter information in parentheses is given when creating the object self.name=name #The initial value of the instance property becomes a parameter self.sex=sex self.age=age pass ''' Example method: eating behavior ''' def eat(self,food): #self is equivalent to the created instance object itself. The food parameter needs to be given when calling the eat function print(self.name+'Like to eat'+food) #print('{} likes to eat {}'. format(self.name,food)) pass zp=People('Peng Zhang','male',19) #Create an object zp and give the data required by the parameters in the instance properties print(zp.name,zp.age,zp.sex) #Print the properties of the object zp zp.eat('Banana') #When calling the instance method, you need to give the data of the parameter food of the instance method eat -- banana lh=People('Li Hui','male',27) print(lh.name,lh.age,lh.sex) lh.eat('a mandarin orange') xh=People('floret','female',38) print(xh.name,xh.age,xh.sex) xh.eat('Durian')
Summary [_ init method]:
- Built in functions of python Magic method with special functions wrapped with double underscores
- It is an initialization method, which is mainly used to define some instance properties and initialization data. It is called automatically when creating an object without manual call
- Using its parameter passing mechanism can make our definition more powerful and convenient
self understanding
- Self is the same memory address as the object. It can be considered that self is the reference of the object - self represents the instance object itself
class Person: def __init__(self,pro): #There are two parameters. The second parameter is given when the object is created self.pro=pro #Definition of instance properties pass def eat(self,name,food): #It can be self or others # print('self=%s'%id(self)) print('%s Like to eat%s,Major is%s'%(name,food,self.pro)) pass pass xm=Person('Psychology') #Create an instance object. The parameters are_ init_ Parameters in #print('address of object xm {} '. format(id(xm))) # Memory address of self in instance method = memory address of instance object # self represents the instance object itself, xm.eat('Xiao Wang','Durian') #If there is only one parameter of self in the defined instance method, you do not need to pass any parameters when calling (self represents the object), you can call it directly
Summary [self features]:
- self is meaningful only when the instance method is defined in the class. When calling, the interpreter does not need to pass in the corresponding parameters, but automatically points to the created object
- The name of self can be changed and can be defined as other names, but the conventional definition is self
- self refers to the class instance object itself, which is equivalent to this in java
Magic method:__ str__ method
If not used__ str__ Method, we print the object directly, and the output result only inherits information similar to id address, such as print object xm:
print(xm) # output<__ main__. Person object at 0x000001B355BFD180>
Use__ str__ Method, you can output specific contents. The usage method is as follows [see below for details]:
# Used as an instance method in a class def __str__(self): return '%s Like to eat%s,Major is%s'%(self.name,self.food,self.pro) pass #You must have a return
Magic method:__ new__ method
In the new magic method, if used in the class:
def __new__(cls, *args, **kwargs): print('----new Function execution-----') #Do not write return object__ new__ (cls) #Output: ----new Function execution----- #The new function was executed None #However, if the init function is not executed, the object is not created successfully
Full code:
class Person: def __init__(self,pro,name,food): #There are two parameters. The second parameter is given when the object is created ''' :param pro:major :param name: full name :param food: food ''' self.pro=pro #Definition of instance properties self.name=name self.food=food print('------init Function execution----') pass ''' Define class ''' def eat(self): #It can be self or others ''' Example method :return: ''' # print('self=%s'%id(self)) print('%s Like to eat%s,Major is%s'%(self.name,self.food,self.pro)) pass def __str__(self): #Magic method: when directly outputting the object, you can output the content, not the address ''' Print object custom object is in content format, not in memory address format :return: ''' return '%s Like to eat%s,Major is%s'%(self.name,self.food,self.pro) pass def __new__(cls, *args, **kwargs): ''' Each time a method that creates an object instance is called, a new object is generated cls namely class Abbreviation of Scenario: you can control some attributes of the created object, which are often used in singleton mode :param args: :param kwargs: ''' print('----new Function execution-----') return object.__new__(cls) #Create an object (in cls class) and return it to init function [must have return] xm=Person('Psychology','Xiao Ming','Durian') #Create an instance object. The parameters are_ init_ Parameters in print(xm) #Direct output object (content format). If not_ str_ Instance method, the direct output is the address #Output: ----new Function execution----- ------init Function execution---- Xiao Ming likes to eat durian. His major is psychology
__ new__ and __ init__ Difference between functions
- __ new__ Class instantiation method: the instance must be returned, otherwise the object creation will not succeed
- __ init__ It is used to initialize data attributes. It can also be regarded as the construction method of instances. It receives the instance self of the class and constructs it
- __ new__ At least one parameter must be cls, which represents the class to be instantiated. This parameter is automatically provided by the python interpreter when instantiating, and does not need to be considered as
- __ new__ Function executed before__ init__ function