Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to master Python built-in methods and attribute applications

2025-04-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to master Python built-in methods and attribute applications". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Preface

In addition to the rich third-party libraries, python also provides some inherent methods and underlying properties, such as dict, list, set, min, max, range, sorted and so on.

two。 Introduction to built-in methods and functions

Enumerate

If you need to iterate through an object that can be iterated, if you need to get its sequence number, you can 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 4 # 1 2 3 # 2 3 4 1

Zip zip combines elements from multiple iterators in the parameters to form a new iterator.

# add the serial number b = [4,3,2,1] for i in zip (range (len (b)), b): print (I) # (0,4) # (1,3) # (2,2) # (3,1) to list

Globals (): a dictionary that describes the global symbol table in the current execution, which shows all the processes you have executed

Id (object): unique identification of the python object

Comments on static functions of staticmethod class

@ staticmethod def test (): print ('this is staticmethod') Foo.test = test Foo.test ()

Class properties let's take a 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') # lists all members and attributes of the 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__' Comments of the 'run'] # class Foo.__doc__ #' this is test class' # class custom attribute Foo.__dict__ mappingproxy ({'_ module__':'_ main__','_ _ doc__': 'this is test class',' _ _ init__':, 'run': '_ _ dict__':,' _ _ weakref__':}) the parent class of the # class Foo.__base__ # the name of the class Foo.__name__

Instantiation and initialization of class

# python class is instantiated by _ _ new__, and then _ _ init__ is called to initialize class member foo = Foo ('milk')

Add and access properties of the class

# access foo.name foo.run () # you can dynamically add attributes def method (): print ("cow") setattr (foo, "type", "cow") setattr (foo, "getcow", method) # cow foo.type foo.getcow () # dynamically delete attributes delattr delattr (foo) through setattr "type") # getattr get member attribute if hasattr (foo, "run"): # determine whether there is an attribute func = getattr (foo, "run") func ()

3. Singleton mode application

Singleton pattern (Singleton Pattern) is one of the simplest design patterns in Java. The singleton pattern requires that it be instantiated only once during the use of the class, and all objects share one instance. The way to create an instance is to determine whether the instance has been passed or return the instantiated global instance. How is python implemented? The key is to find the place to instantiate, yes, the _ _ new__ mentioned earlier.

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

4. Reflection application

Reflection is used in many frameworks, simply by instantiating the 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 timed task class, and instantiating the class and executing tasks by reflection when the execution time is due, which is also very common in java.

The implementation of python can get the class in the module through the getattr mentioned above and call the method through 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 class # resides. Default is _ _ main__ " You can get the class in the api_module = importlib.import_module ('_ _ main__') # getattr acquisition module through'_ _ module__' in Foo.__dict__, where Foo is the string oh clazz = getattr (api_module, 'Foo') # instantiated params = ["milk"] instance = clazz (* params) # method call, and the method is also the string methodcaller (method name) Method parameters) task_result = methodcaller ("run", "reflection") (instance) # running reflection "how to master the application of Python built-in methods and properties" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report