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 use the reflection of python object-oriented programming

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "how to use the reflection of python object-oriented programming". In the daily operation, I believe that many people have doubts about how to use the reflection of python object-oriented programming. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to use the reflection of python object-oriented programming". Next, please follow the editor to study!

About namespaces

What we talked about yesterday are mainly getattr, hasattr, setattr, delattr and callable functions. There is a key word-namespace, which is a very important concept. To learn more about python, you must have a very clear understanding of namespaces.

A namespace is a named memory space that a python program requests from the operating system at run time. If we think of memory as a building, then when the python interpreter executes the script (the currently executed py file), it will apply for a floor to store the data and code blocks in the currently executed py file. The namespace is called _ _ main__. If a class is defined in this file, a separate room is created for the class on the floor to store the data and code blocks inside the class. The name of the room is the class name. When you create an instance of a class, you will also open a separate room for the instance, in which the properties of the instance and the class pointer are stored. When you access the properties of the instance, look in the namespace of the instance. When you access the binding method of the instance, use the class pointer to find it in the room of the class. The name of the room is the name of the instance. Assuming that we import other modules, then the python interpreter will apply to the system for a new floor to store the imported py file. Similarly, it can be inferred that the newly imported py file may also define classes and create instances of classes. Those classes and their instances are stored on the new floor, the new floor name is the py file name.

The following are explained in detail through cases and legends:

There is an animal_file.py file with the following contents:

Class Animal:kind = 'animal' def _ init__ (self, name): self.name = namedef eat (self): print (f'{self.name} is eating!')

There is also a run.py file that reads as follows:

Import animal_fileclass Cat (animal_file.Animal): def _ init__ (self, name, count=0): self.count = count animal_file.Animal.__init__ (self, name) def mousing (self): print (f'cat "{self.name}" caught {self.count} mice') white_cat = Cat ('big white cat') white_cat.mousing () out: cat "big white cat" caught 0 mice

The figure of the example is as follows:

When executing the run.py file, you will first apply for a namespace named _ _ main__; when you execute the import animal_file statement, you will apply for a new namespace called animal_file, and when you import the contents of the file, you will open up a namespace called Animal class in the namespace of animal_file, with kind variables, _ _ init__ method and eat method inside. After import, you will return to the run.py file to continue execution. Class Cat (animal_file.Animal): when executing a statement, a namespace named Cat is opened in the namespace of _ _ main__, and there are parent class pointers, _ _ init__ methods and mousing methods pointing to the Animal class. When creating a white_cat instance, a namespace named white_cat is opened in the namespace of _ _ main__, and there are pointers, name attributes and count attributes pointing to this class.

The above is about the contents of the namespace and code examples, legends explain in detail, the concept of namespace is not clear friends must not be verbose, patiently read and understand, it is best to try to draw their own, be sure to make the concept of namespace clear.

Instance 1 of reflection-login authentication

The code is as follows:

Class Authentic:lst = [('login', 'login'), (' registration', 'register'), (' list', 'table')] def _ _ init__ (self, name) Pwd): self.name = name self.pwd = pwd self.table = 'Test list' def register (self): name = input ('Please enter user name:') pwd1 = input ('Please enter password:') pwd2 = input ('Please enter again:') if pwd1 = = pwd2 and len (pwd1) > 5:self.name = name self.pwd = pwd1print (f' registered account "{name}" successful') else : print ('two passwords are inconsistent or the password length is less than 6 Registration failed') def login (self): name = input ('Please enter username:') pwd = input ('Please enter password:') if pwd = = self.pwd and name = = self.name:print (f 'login account "{name}" success') else:print ('username or password is incorrect, login failed!') user = Authentic ('abc',' 123456') while 1:for j I in enumerate (Authentic.lst): print (f'{jig1}. {I [0]}','\ tasking, end='') print () ret = input ('Please enter your choice:') if ret.upper () = 'Q':breakelse:try:choice = Authentic.lst [int (ret)-1] [1] if hasattr (user, choice): if callable (ret: = getattr (user, choice): ret () else:print (ret) except (IndexError, ValueError): pass:

The above is a minimalist example of login verification. Two methods login and register are defined in the Authentic class, and there are three corresponding menu options. Next, initialize the instance user, then enter the loop, and the loop body begins to print a list of options, and then accepts user input; exit the loop if you judge whether the input is'Q' or'Q'. Otherwise, try to convert the input to a number and use it to value the list (errors that occur when the index is out of bounds or are not of a numeric type are ignored). After a successful value, the content of choice is one of the strings' login' or 'register' or' table', then judge the value of choice, execute it if it can be executed, and print it if it cannot be executed.

The above is a simple example of using reflection. At first glance, it is mediocre, so compare the code that does not use reflection to achieve the same function:

User = Authentic ('abc',' 123456') while 1:for j, i in enumerate (Authentic.lst): print (f'{jig1}. {I [0]}','\ tasking, end='') print () ret = input ('Please enter your choice:') if ret.upper () = = 'Q':breakelif ret = =' 1':user.login () elif ret = '2':user.register () elif ret =' 3':print (user.table)

Please think carefully. The current list of options is 3, and elif has been used 3 times. If there are dozens of options, will the code add dozens of elif as the list of options increases? Looking back at the code implemented with reflection, there is no need to add elif judgment whether the list of options is 3, 30, or even 300.

Example of reflection 2Mui-file operation

3 lines of code to achieve file operation script, now try to create a new py file, the content is as follows, the file is called f.py

Import shutilfrom sys import argvgetattr (shutil, argv [1]. Lower ()) (argv [2], argv [3])

Then open the cmd window and go to the directory where the f.py file is located.

Execute the following command:

Python f.py copy f.py fpy.bakpython f.py move fpy.bak f1.pypython f.py rename f1.py f2.py

After each execution, you can check whether the command is executed properly.

How to get the name content of the current script

With regard to reflection, we all know that you can use getattr to get the contents of the specified name in the specified namespace, but how do you get the name content of the current script? First import sys, then use sys.modules ['_ _ main__'] to get the namespace of the current script.

Suppose there is a small demand, the value of a variable is 123, the value of b variable is 123, the value of b variable is abc', and the value of b variable is 123, and the value of b variable is 123.

Import sysa = 123b = 'abc'ret = input (' Please enter the name to print:') if hasattr (sys.modules ['_ main__'], ret): print (getattr (sys.modules ['_ main__'], ret))

Imagine if there are dozens of variable names, do you need to write dozens of lines in the usual way of writing if elif else? A lot of if eilf else can be done with a simple reflection of two lines of code.

At this point, the study on "how to use the reflection of python object-oriented programming" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report