Object oriented Python (object methods, class methods, static methods, magic methods)

 

object-oriented:

1. All class names shall be capitalized, and hump naming shall be used when there are multiple words

2. The ancestor of all custom classes is object

3. There are four methods in the class: ordinary method, class method, static method and magic method.

##Simple object-oriented example

class car:  #Automatically inherited object
    brand = 'red flag'

print(car)
#Create objects using classes (reproduce with a template)
jsy = car()  #Object generation
print(jsy)

print(jsy.brand)    #Use the properties defined in the class
jsy.brand = 'Tesla'   #Use the properties in the class and define their own values
print(jsy.brand)

Output:

<class '__main__.car'>
<__main__.car object at 0x000001996AABBFD0>
red flag
 Tesla

Properties:

Attributes can be divided into class attributes and object attributes

class Student:
    #Class properties
    name = 'Jack'
    age = 18

JSY = Student()
JSY.gender = 'male'
print(JSY.gender)

#Modifying properties in a class
Student.name = 'JackLove'
print(JSY.name)  #There is no name defined in the JSY object, so the attribute name in the class is used

Output:

male
JackLove

Note: when an object calls an attribute, first find it in the object attribute (its own space), and then find it in the class attribute (model space)

            For class properties, each object can be called

Normal (object) method:

Format:

def   Method name (self, [parameter, parameter]):

        Method content

class Phone:
    brand = 'HuaWei'
    price = 3999
    type = 'nava 4'

    #Method in Phone: call
    def call (self):
        print(self)  #self is the object that calls the function
        print('Calling...')
        print('Master:',self.name)

phone1 = Phone()
phone1.name = 'Jack'

print(phone1)
phone1.call()  #self in the call method means that whoever calls the call function will pass itself as a parameter to call

Output:

<__main__.Phone object at 0x000001560191BE80>
<__main__.Phone object at 0x000001560191BE80>
Calling...
Master: Jack

Note: ordinary functions can be called with the class name, but the parameter should be the object name: Phone.call(phone1)

Class method:

Format:

@classmothod

def test(cls, [parameter], [parameter]):

   pass

characteristic:

1. The definition needs to depend on the decorator @ classmothod

2. Class methods can only use class attributes, not object attributes

3. Object methods cannot be called in class methods, and class methods can be called in object methods

4. The parameter of a class method is not an object (self), but a class (cls)

Class method function:

Class methods can only access class properties and other class methods, so class methods can be used if some actions (functions) need to be completed before object creation.

Class methods are object independent and independent methods.

###Examples

class Dog:
    def __init__(self,nickname):
        print('init')
        self.nickname = nickname

    def run(self):  #self object | object method
        print(self)    #Printing is the object name and object space
        print('{}be sleeping!'.format(self.nickname))
        Dog.test()   #In object methods, class methods can be called by class name or object (self)
        self.test()

    def eat(self):
        print('Are you hungry...')
        self.run()

    @classmethod  #Decorator
    def test(cls):   #CLS class 𞓜 class method
        print(cls)     #Print is the class name
        # print(cls.nickname)   #There is no parameter nickname in class space

print(Dog)
Dog.test()  #Class methods do not depend on objects and can be called before objects appear
dog = Dog('Wangcai')
# dog.run()

dog.eat()

Output:

<class '__main__.Dog'>
<class '__main__.Dog'>
init
 Are you hungry...
<__main__.Dog object at 0x0000015D8D4FCFA0>
Wangcai is sleeping!
<class '__main__.Dog'>
<class '__main__.Dog'>

It can be seen that in ordinary methods, class methods can be called by class name or object  

            You cannot call the properties of an object in a class method. You can only call class properties

            Class methods are not object dependent and can be called by class name before object creation

            Objects can call class methods and object (normal) methods; But a class can only call class methods

Static method:

Format:

@staticmethod

def test():

   pass

characteristic:

1. Need decorator @ staticmethod

2. Static methods do not need to pass parameters (cls,self, etc.)

3. You can only access the properties and methods of the class (use the class name to call static methods, or call the private properties of the class through the class name)       The object's properties are inaccessible

4. The loading time is the same as that of similar methods, and it is similar to that of class methods

##Examples

class Person:
    __age = 21  #Property is privatized and cannot be accessed by the outside world through the class

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

    def show(self):
        print('Age:{}'.format(self.__age))  #At this time__ age can be accessed through (object method) self to encapsulate data

    @classmethod
    def update_age(cls):
        cls.__age = 18     #It can also be accessed through cls (with the help of class methods)
        print("Class method")

    @classmethod
    def show_age(cls):
        print(cls.__age)

    @staticmethod
    def test():  #Self and CLS cannot appear without its own parameters
        print('Static method')
        print(Person.__age)


p = Person('Jack')
p.update_age()
p.show()
Person.update_age()
Person.show_age()
Person.test()

Note: when defining an attribute in a class, adding two underscores before the attribute name will define it as a private attribute (inaccessible to the outside world)

          

Output:

Class method
 Age: 18
 Class method
18
 Static method
18

Summary:

Class method   And   Static method

Different:

1. Different decorators

2. Class methods have parameters and static methods have no parameters

Same:

1. They can only access class properties and methods, and can call each other through class names. Objects cannot be accessed

2. Can be called by class name

3. All can be used before creating objects, because they do not depend on objects

Differences between ordinary () object methods and the two:

1. There is no decorator in the common method

2. Ordinary methods always depend on objects, because every ordinary method has a self

3. Ordinary methods can be called only after the object is created

Magic method:

All double underlined '' The wrapped method is called magic method. The magic method will be executed automatically under certain conditions.

Common magic methods:

__ init__: Initialize magic method

Trigger timing: triggered when initializing an object (different from instantiation, but in the same operation as instantiation)

__ new__: (must have return value) magic method for object instantiation, opening up memory space and returning object instance (address space)

Trigger timing: triggered during instantiation

__ call__: Call object methods (make objects callable as functions)

Trigger timing: triggered when an object is called as a function. The contents of the function are executed by default

__ del__: Deconstruction magic method     # Understand the garbage collection mechanism in Python

Trigger timing: triggered when the object has no variable reference (useless)

__ str__: There must be a return value. Pass the return value to the object

Trigger timing: automatically trigger the call when printing the object name__ str__

For__ init__ And__ new__ Operation mechanism of:

When defined in a class__ init__ And__ new__ Time

1. When creating an object, execute__ new__ , Open up a space and pass the space address as a return value to__ init__

2. Re execution__ init__, self is the open address space

3. Completion of implementation__ init__ After that, the address space of self is passed to the object

##Examples

class Person:
    def __init__(self, name): #Initialize instance
        print('init')
        print(self)
        self.name = name
        print(name)

    def __new__(cls,*args,**kwargs): #To create and return an instance of this class, you must have a return value
        print('Magic method:_new_',args)
        # return super(Person, cls).__new__(cls)  #Return value to_ init_ self in
        space = object.__new__(cls)   #The function is the same as above
        print(space)
        return space

    def __call__(self, name):
        print('Magic method:__call__')
        print('The parameters passed in by the execution object are:',name)

p = Person('Jack')  # Trigger first_ new_ Method to instantiate an object; Re trigger_ init_ method
print(type(p))
print(p)

p('jsy')  #Treat the object as a function call

Output:

Magic method:_new_ ('Jack',)
<__main__.Person object at 0x000001FA562CCF70>
init
<__main__.Person object at 0x000001FA562CCF70>
Jack
<class '__main__.Person'>
<__main__.Person object at 0x000001FA562CCF70>
Magic method:__call__
The parameters passed in by the execution object are: jsy

Note: in use__ new__ You need to create and return an instance of this class, but python2 and python3 are different for super functions               How to write: Python 3__ new__ () no other parameters. Write__ new__(cls).

            For__ call__ Method, the parameter is self, which is related to the object. When the object is called in a functional way, the               The method is triggered automatically, and return values are allowed.

For__ del__ Description of magic method:

1. Object assignment

   p = Person()

    p1 = p          # P and P1 point to the same address together

2. Delete address reference

    del   p1         # Delete P1 reference to address

3. View the number of references of the object

   import  sys

   sys.getrefcount(p)

4. When there is no reference in a space, it is executed by default__ del__ ()

(Python has its own garbage collection mechanism, which automatically releases resources every time the program is executed, so it will be executed automatically after the program is completed _del_)

##Examples

import sys
class Man:
    def __init__(self,name):
        self.name=name

    def __del__(self): #After deleting the reference and executing the remaining code, execute it_ del_
        print('Magic method: del')
p = Man('J')
p1 = p
p2 = p
print(p,p1)
print(p1.name)
print(sys.getrefcount(p1))

p1.name = 'Tom'
print(p1.name,p.name)  #If you change the value of one of them, the other variables pointing to the address will also change

print(p2)

Output:

<__main__.Man object at 0x000001B9B448CBE0> <__main__.Man object at 0x000001B9B448CBE0>
J
4
Tom Tom
<__main__.Man object at 0x000001B9B448CBE0>
Magic method: del

It can be seen that p, p1 and p2 point to an address space together, and if the value of one of them is modified, the other variables pointing to the address will also change.

__ del__ The execution of is performed only after the reference is deleted and all code is executed

For__ str__ Description of magic method:

For developers, simply print the object name and output the address space of the object (it doesn't make much sense), so use__ str__ To pass in the desired information (value) to the object.

##Examples

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

    def __str__(self):
        return 'full name:'+self.name+'Age:'+self.age  #Return value to object

p = Human('JSY','22')  #The object p value is__ str__ Return value of
print(p)

Output:

full name: JSY Age: 22

Note: use__ str__ There must be a return value, and the return value should be in string form, which is triggered when the object name is printed

Tags: Python Pycharm

Posted on Tue, 23 Nov 2021 22:13:52 -0500 by KingWylim