This post is part of the third session of the Nuggets Creators Training Camp.Digg project | Creator Boot Camp phase 3 is underway, “write” to make a personal impact.

📖 preface

Sanmao once sighed:

“What is the mind like? There is a labyrinth that stretches thousands of miles across. There is no boat that can ferry people. Throughout life, we are learning how to be our own ferrymen.

You can watch this blogger’s article about installation and LocalizationVsCode download, Installation and LocalizationAs well asPython series: windows10 configuration Python3.0 development environment!After installation, restart VsCode!

This article mainly introduces various properties defined in a class, such as class properties, instance properties, private properties of a class, and various methods, such as instance methods, class methods, static methods and property property methods.


🚀 start

This paper mainly introduces the object-oriented programming class magic attributes, these magic attributes have its special function, that is, when executing some operations, will automatically trigger the execution of these magic methods, understand these magic methods can better understand the realization principle of object-oriented programming;

Before we look at magic methods, let’s look at two other methods:

isinstance()issubclass()

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: demoone.py @time: 2019/10/30 08:52:50 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib

class A(object) :
    pass
class B(A) :
    pass

b = B()

# isinstance(o,c) -- determine if the former is an object created by the latter
print(isinstance(b,A))  # True
print(isinstance(b,B))  # True

# issubClass -- Determine if the former is a subclass of the latter
print(issubclass(B,A))  # True
Copy the code

Reflection:Hasattr, getattr, setattr, delattrFour built-in functions

  • Reflection, also known as introspection (self-reflection), was first proposed by Smith in 1982. It refers to the ability of a program to access, detect and modify its own state or behavior.
#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: fanshedemo. py @time: 2019/10/30 08:54:08 @author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


class Programmer(object) :
    "" define a programmer class ""
    character = "intelligent"  # Characteristics: Smart

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

    def write_code(self) :  # to write the code
        pass

    def debug(self) :  # debugging
        pass


p = Programmer("Mr_Chen".21."male")

# hasttr - See if the object can use this property or method
print(hasattr(p, "name"))
print(hasattr(p, "debug"))

# getattr - Get object attributes
print(
    getattr(p, "write_code"))#<bound method Programmer.write_code of <__main__.Programmer object at 0x0000016F87ABBFD0>>
print(getattr(p, "character"))  # == p.character

# You can specify a third parameter that will be returned without error if the attribute does not exist
# print(getattr(p,"balabala")
print(getattr(p, "balabala"."Nonexistent"))

# setattr - Modifies object properties
setattr(Programmer, "character"."handsome")  # == Programmer.character = "handsome"
print(p.character)  # handsome

# delattr - Remove this attribute
delattr(p, "name")  # == del p.name
print(p.__dict__)  #{'age': 21, 'gender': 'male'
delattr(Programmer, "debug")
print(Programmer.__dict__)  The #debug attribute is gone
Copy the code

Advantages of reflection: A pluggable mechanism can be implemented, for example: In the actual project development process, usually multiple programmers with A large area to complete the project, if the programmer in the process of development requires A programmer B classes defined, B asks for leave to accompany the wife gave birth to A child, but the programmer code is not complete, this time the programmer can use B reflection mechanism to continue to complete your own code, such as:

#! /usr/bin/env python
# -*- encoding: utf-8 -*-
@file: yuandemo1.py @time: 2019/10/30 08:56:26@author: YongJia Chen @version: 1.0 @contact: [email protected] @License : (C)Copyright 2018-2019, Liugroup-NLPR-CASIA @Desc : None '''

# here put the import lib


# programmer A --moduleA
class A(object) :
    def __init__(self, x, y) :
        self.x = x
        self.y = y


# -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
# programmer B
from moduleA import A
a = A(10.20)
if hasattr(a, "cal") :# Judge whether there is such a calculation method, regardless of whether it does not affect my writing and debugging of other logic
    print(a.cal())
else:
    print("The calculation method is not defined.")
    print("Go ahead and execute other logic.")
Copy the code

Magic methods

__doc__ Displays the description of the classCopy the code
class Foo(object) :
    "" This is an introduction and description of this class. ""
    pass

print(Foo.__doc__)  # This is an introduction and description of this class
Copy the code
__module__ and __class__ look at the module of the class being operated on, and __class__ look at the class of the current object.Copy the code
class Bar(object) :
    pass

b1 = Bar()
print(Bar.__module__)  # __main__ ---- Specifies the module where the current file resides
print(Bar.__class__)  # <class 'type'>
print(b1.__class__)  # <class '__main__.Bar'>

Bar is instantiated from type and b1 is instantiated from the current module's Bar class
Copy the code
The __init__ constructor automatically triggers the execution of the __init__ method when instantiated into an object by a class. The properties defined in this method are instance properties, which automatically create a memory space for storing the properties of the instance object and Pointers to the class methods.Copy the code
class Foo(object) :
    # construct method
    def __init__(self,name) :
        self.name =name
        print("in the init")

foo = Foo("sunny chen")   # in the init
Copy the code
The __del__ method triggers execution automatically when instance objects created by this class are deleted or released from memory.Copy the code
class Foo(object) :
    # destructor method
    def __del__(self) :
        print("in the __del__")

foo = Foo()
del foo  # in the __del__
Copy the code

This method does not need to be defined because Python is a high-level language and programmers do not need to worry about allocating and freeing memory. This is all done by the Python interpreter, so destructor calls are automatically triggered by the interpreter when garbage collection is performed. Of course, when I redid the destructor above, there would be no real memory reclamation, and a lot of the underlying implementation would be encapsulated.

5.

The __call__ object is parenthesized to trigger execution.Copy the code
class Bar(object) :
    pass

bar = Bar()
# bar() # TypeError: 'Bar' object is not callable

When a class has a __call__, the instantiated object is callable
class Foo(object) :

    def __call__(self) :
        print("in the call")

foo = Foo()
foo()  # in the call
Copy the code

Constructor execution is triggered by creating an object: object = class name (); And forcallMethod execution is triggered by parentheses following the object: object () or class ()()

The __dict__ attribute dictionary of a class or instance that holds the attributes and methods of the class or instance;Copy the code
class Bar(object) :
    gender = "male"
    def __init__(self,name) :
        self.name = name
    def tt(self) :
        pass

bar = Bar("sunny chen")
print(Bar.__dict__)
# output is: {' __module__ ':' __main__ ', 'gender' : 'male', '__init__ : < the function Bar. __init__ at 0 x0000020f94f10b70 >,' tt: 
      
       , '__dict__':
      
# <attribute '__dict__' of 'Bar' objects>, '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__doc__': None}

print(bar.__dict__)
#{'name': 'sunny chen'}
Copy the code

The attribute dictionary stores the attributes of class objects and their corresponding values, methods and their corresponding method Pointers in the form of key-value pairs.

The __str__ methodCopy the code
class Bar(object) :

    def __str__(self) :
        return "<bar object <Bar> at 000000xxxx>"

If a class defines a __str__ method, the return value of that method is printed by default when the object is printed.
bar = Bar()
print(bar)  # <bar object <Bar> at 000000xxxx>


This is also true for other objects, when printing the object to give the user a hint
import threading
def test() :
    pass
t = threading.Thread(target=test)
print(t)  #<Thread(Thread-1, initial)>
Copy the code

When the user does not know what the instance object is, it automatically prints the class’s internal __str__ method to give the user a hint.

__getattr__, __setattr__, __delattr__Copy the code

While we look at these three magic methods, let’s take a look at a concept called reflection, which is achieved through four built-in functions, i.eHasattr, getattr, setattr, delattr; In fact, when we call the last three methods, we execute the magic method of the class; Such as:

#---------------- copy---------------
class Foo:
    x=1
    def __init__(self,y) :
        self.y=y

    def __getattr__(self, item) :
        print('----> from getattr: the attribute you are looking for does not exist ')


    def __setattr__(self, key, value) :
        print('----> from setattr')
        # self.key=value # this is infinitely recursive, so think about it
        # self.__dict__[key]=value # It should be used

    def __delattr__(self, item) :
        print('----> from delattr')
        # del self.item # infinite recursion
        self.__dict__.pop(item)

#__setattr__ Adding/modifying attributes triggers its execution
f1=Foo(10)
print(f1.__dict__) # Because you overwrite __setattr__, any assignment will trigger it to run, you write nothing but no assignment at all, unless you directly manipulate the attribute dictionary, you will never be able to assign
f1.z=3
print(f1.__dict__)

Raised when the #__delattr__ attribute is deleted
f1.__dict__['a'] =3We can add/modify attributes directly by modifying the attribute dictionary
del f1.a
print(f1.__dict__)

#__getattr__ is only raised if the attribute is called with a point and does not exist
f1.xxxxxx
Copy the code
__getitem__, __setitem__, delitem__Copy the code

The use of the attR magic method is similar to that of the previous three methods, except that the method of triggering is different. The attR magic method is triggered by the dot “. “, while the item magic method is triggered by the dictionary “[]”. Such as:

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

    def __getitem__(self, item) :
        print(self.__dict__[item])

    def __setitem__(self, key, value) :
        print("in the setitem.")
        self.__dict__[key]=value

    def __delitem__(self, key) :
        print('in the delitem.. ')
        self.__dict__.pop(key)

    def __delattr__(self, item) :
        print('in the delattr.. ')
        self.__dict__.pop(item)

# obj.["key"] triggers the __xxxItem__ magic method
f1=Foo("sunny chen")
ret = f1["name"]  # trigger __getitem__ execution
f1["age"] =18   # Trigger __setattr__ execution


del f1['age']  # Trigger __delitem__ execution
f1['name'] ='sunny'
del f1.name  # trigger __delattr__ execution
print(f1.__dict__)
Copy the code
  1. Of course,Iterators and generators;

Go and try it!


🎉 finally

  • For more references, see here:Chen Yongjia’s blog

  • Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!