\

1. Introduction

In addition to rich third-party libraries, Python itself also provides some internal methods and some underlying attributes, such as dict, list, set, min, Max, range, sorted and so on. The author recently involved some methods and attributes that are not very commonly used in the project framework. I would like to share them with you in this article.

2. Introduction to built-in methods and functions

  • enumerate

    If you need to iterate over an iterable object and obtain its ordinal number, use enumerate. Each next returns a tuple

    list1 = [1.2.3.4]
    list2 = [4.3.2.1]
    for idx, value in enumerate(list1):
        print(idx, value, list2[idx])
    # 0 1 41 2 32 3 23 4 1
    Copy the code
  • Zip Zip takes elements from multiple iterators in parameters and combines them into a new iterator;

    List = [4.3.2.1]
    for i in zip(range(len(b)), b):
        print(i)
    # (0.4)
    # (1.3)
    # (2.2)
    # (3.1)
    Copy the code
  • Globals () : A dictionary describing the global symbol table for the current execution, showing all the procedures you are executing

  • Id (object) : Unique identifier of a Python object

  • Staticmethod class static function annotations

    @staticmethod  
    def test(): 
        print('this is static method')
    
    Foo.test = test
    Foo.test()
    Copy the code
  • Let’s look at the next class declaration, as follows:

    class Foo():
        """this is test class"""
        def __init__(self, name):
            self.name = name
        
        def run(self):
            print('running')
    Copy the code
    # list all members and attributes of class dir(Foo) ['__class__'.'__delattr__'.'__dict__'.'__dir__'.'__doc__'.'__eq__'.'__format__'.'__ge__'.'__getattribute__'.'__gt__'.'__hash__'.'__init__'.'__init_subclass__'.'__le__'.'__lt__'.'__module__'.'__ne__'.'__new__'.'__reduce__'.'__reduce_ex__'.'__repr__'.'__setattr__'.'__sizeof__'.'__str__'.'__subclasshook__'.'__weakref__'.'run'] # class annotation foo.__doc__ #'this is test class'# class custom attribute Foo.__dict__ mappingProxy ({'__module__''__main__'.'__doc__''this is test class'.'__init__': <function __main__.Foo.__init__(self, name)>,
              'run': <function __main__.Foo.run(self)>,
              '__dict__': <attribute '__dict__' of 'Foo' objects>,
              '__weakref__': <attribute '__weakref__' of 'Foo'Objects >}) # class parent class Foo __base__ # class name Foo __name__Copy the code

    Class instantiation and initialization

    # Python class foo = foo (instantiated by __new__ and initialized by __init__)'milk')
    Copy the code

    Class to add and access properties

    Foo. Name foo. Run () # Def method() can be added dynamically via setattr:print("cow")
    
    setattr(foo, "type"."cow")
    setattr(foo, "getcow", method)
    # cow
    foo.typeFoo. Getcow () # delattr delattr(foo,"type") # getattr gets the member attributesif hasattr(foo, "run"): # check if there is an attributefunc = getattr(foo, "run")
        func(a)
    Copy the code

3. Singleton application

The Singleton Pattern is one of the simplest design patterns in Java. The singleton pattern requires that the class be instantiated only once during its use, with all objects sharing one instance. The method of creation is to determine whether the instance has been instantiated at the time of the instance and return the instantiated global instance if it has been instantiated. How does Python work? The key is to find where to instantiate, which is __new__

class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls)
        return cls._instance
    
    def __init__(self, name):
        self.name = name


a = Singleton('name1')
b = Singleton('name2')
print(id(a), id(b))
print(a.name, b.name)
# 1689352213112 1689352213112
# name2 name2
Copy the code

4. Reflection applications

Reflection is used in many frameworks, simply by instantiating a class by its name (string). A typical scenario is to dynamically control the execution of classes through configuration, such as the execution of scheduled tasks. By maintaining the execution time of each scheduled task class, when the execution time is up, the class is instantiated through reflection to execute the task, which is also very common in Java.

Python implementations can get classes in modules using getattr, as described above, and call methods using methodCaller. Let’s look at a simple example

import importlib
from operator import methodcaller

class Foo():
    """this is test class"""
    def __init__(self, name):
        self.name = name
    
    def run(self, info):
        print('running %s'% info) # the module in which the class resides, __main__ by default, can be passed in foo. __dict__'__module__'Get api_module = importlib.import_module('__main__'Clazz = getattr(api_module,'Foo'Params = ["milk"[instance = clazz(*params) # task_result = clazz(*params)"run"."reflection")(instance)

# running reflection
Copy the code

5. To summarize

This article shares Python’s built-in methods and properties and applies them in singleton patterns and reflection. The main points of @mintel are summarized below:

  • Under the dir class
  • View the class custom attribute __dict__
  • __new__ instantiates the class, __init__ initializes the class
  • Getattr gets the property
  • Setattr Sets properties
  • Remember importlib and methodCaller

About the author: WeDO Experimental Jun, data analyst; Love life, love writing

Appreciate the author

Python Chinese community as a decentralized global technology community, to become the world’s 200000 Python tribe as the vision, the spirit of Chinese developers currently covered each big mainstream media and collaboration platform, and ali, tencent, baidu, Microsoft, amazon and open China, CSDN industry well-known companies and established wide-ranging connection of the technical community, Have come from more than 10 countries and regions tens of thousands of registered members, members from the ministry, tsinghua university, Peking University, Beijing university of posts and telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, cicc, huawei, BAT, such as Google, Microsoft, government departments, scientific research institutions, financial institutions, and well-known companies at home and abroad, nearly 200000 developers to focus on the platform.

Recommended reading:

Read common cache problems in high concurrency scenarios \

Using Django to develop DApp\ based on Ethereum smart contract

Let’s read Python tasks like celery\

5 minutes on chain calls in Python

Create a Bitcoin price alert application in Python

Click to read the original article, namely enjoy Aliyun product discount of 0.9 percent