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 special properties and methods of python

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

Share

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

This article mainly explains "how to use the special properties and methods of python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the special properties and methods of python.

Python uses underscores as variable prefixes and suffixes to specify special variables

_ xxx cannot be imported with 'from module import *'

_ _ xxx__ system definition name

Private variable name in _ _ xxx class

Core style: avoid using underscores as the beginning of variable names.

Because underscores have a special meaning to the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid using underscores as the beginning of variable names. Generally speaking, the variable name _ xxx is considered "private" and cannot be used outside the module or class. It is a good habit to use _ xxx to represent a variable when it is private. Because the variable name _ _ xxx__ has a special meaning for Python, this naming style should be avoided for ordinary variables.

The member variables that begin with "single underscore" are called protected variables, which means that only class objects and subclass objects themselves can access these variables.

"double underlining" starts with private members, meaning that only the class object can access it, and even the subclass object cannot access this data.

Class attributes that cannot be directly accessed by the representatives starting with a single underscore (_ foo) need to be accessed through the interface provided by the class and cannot be imported with "from xxx import *"; the (_ _ foo) beginning with a double underscore represents the private members of the class; and the (_ _ foo__) beginning and ending with a double underscore represents the identity specific to the special method in the python, such as _ _ init__ () represents the class constructor.

Now let's summarize all the system-defined properties and methods, let's first look at the reserved properties:

> Class1.__doc__ # type help information 'Class1 Doc.' > Class1.__name__ # type name' Class1' > Class1.__module__ # type module'_ _ main__' > base class inherited by the Class1.__bases__ # type (,) > Class1.__dict__ # type dictionary to store all type member information. > Class1 (). _ _ class__ # type > Class1 (). _ _ module__ # instance type module'_ _ main__' > Class1 (). _ _ dict__ # object dictionary, which stores all instance member information. {'irie: 1234} next is the retention method. You can classify the retention method: the base method of the class initializes an instance x = MyClass () x.reserved initworthy _ () string, the "official" representation of the string repr (x) x.reserved reprinters _ () string, the "informal" value str (x) x.reserved strings _ () byte array, the "informal" value bytes (x) x.roomstrings _ () formatted string value format (x). Format_spec) x.formatting formats _ (format_spec)

The call to the _ _ init__ () method occurs after the instance is created. If you want to control the actual creation process, use the _ _ new__ () method.

By convention, the string returned by the _ _ repr__ () method is a legal Python expression.

The _ _ str__ () method is also called when print (x) is called.

It started in Python 3 due to the introduction of the bytes type.

A class that behaves like an iterator traverses a sequence iter (seq) seq.__iter__ () to get the next value from the iterator next (seq) seq.__next__ () creates an iterator reversed (seq) seq.__reversed__ () in reverse order

The _ _ iter__ () method is called whenever an iterator is created. This is an excellent place to initialize iterators with initial values.

The _ _ next__ () method is called whenever the next value is obtained from the iterator.

The _ _ reversed__ () method is not commonly used. It takes an existing sequence as a parameter and arranges all the elements in the sequence from tail to head in reverse order to generate a new iterator.

Calculation property gets a calculation property (unconditional) x.myroompropertyx.calculation gegeattributeproperty _ ('my_property') gets a calculation property (backup) x.myroompropertyx.calculation getattronics _ (' my_property') sets a property x.my_property = valuex.__setattr__ ('my_property') Value) delete a property del x.myroompropertyx.listing all properties and methods dir (x) x.deleted dirties _ ('my_property')

If a class defines a _ _ getattribute__ () method, Python calls it every time a property or method name is referenced (except for a special method name, because that would lead to an annoying infinite loop).

If a class defines the _ _ getattr__ () method, Python will only call it when it queries for properties in its normal location. If instance x defines the property color,x.color, it will not call x.inherit _ tattooed _ ('color'); it will only return the value defined by x.color.

The _ _ setattr__ () method is called whenever a property is assigned a value.

The _ _ delattr__ () method is called whenever a property is deleted.

The _ _ dir__ () method is useful if the _ _ getattr__ () or _ _ getattribute__ () methods are defined. Typically, a call to dir (x) will display only the normal properties and methods. If the _ _ getattr () _ _ method processes the color property dynamically, dir (x) will not list color as an available attribute. You can override the _ _ dir__ () method to allow color to be listed as an available property, which is useful for people who want to use your class but don't want to go deep inside it.

Classes that behave like functions

You can make instances of a class callable-- just as a function can be called-- by defining the _ _ call__ () method.

Call an instance my_instance () my_instance.__call__ () as if you were calling a function

In this way, the zipfile module defines a class that can decrypt encrypted zip files with a given password. The zip decryption algorithm needs to save the state during the decryption process. By defining the decryptor as a class, we can maintain this state in a single instance of the decryptor class. The state is initialized in the _ _ init__ () method and updated if the file is encrypted. But because the class is "callable" like a function, you can pass in the instance as the first argument of the map () function, as follows:

# excerpt from zipfile.py class _ ZipDecrypter: def _ init__ (self, pwd): self.key0 = 305419896 self.key1 = 591751049 self.key2 = 878082192 for p in pwd: self._UpdateKeys (p) def _ call__ (self, c): assert isinstance (c) Int) k = self.key2 | 2 c = c ^ ((k * (k ^ 1)) > & 255) self._UpdateKeys (c) return c zd = _ ZipDecrypter (pwd) bytes = zef_file.read (12) h = list (map (zd, bytes [0:12]))

The _ ZipDecryptor class maintains a state in the form of three rotating keys, which will be updated later in the _ UpdateKeys () method (not shown here).

This class defines a _ _ call__ () method so that the class can be called like a function. In this example, _ _ call__ () decrypts a single byte of the zip file and then updates the rotation password based on the decrypted bytes.

Zd is an instance of the _ ZipDecryptor class. The variable pwd is passed in the _ _ init__ () method, where it is stored and used to rotate the password update for the first time.

Giving the first 12 bytes of the zip file and mapping these bytes to zd for decryption actually results in 12 calls to the _ _ call__ () method, that is, updating the internal state and returning the resulting bytes 12 times.

Classes that behave in a similar manner to the sequence

If a class appears as a container for a series of values-- that is, if it makes sense for a class to "include" a value-- it should probably define the following special method to make it behave like a sequence.

Length of a sequence len (seq) seq.__len__ () knows whether a sequence contains a specific value x in seqseq.__contains__ (x)

The cgi module uses these methods in its FieldStorage class, which represents all form fields or query parameters submitted to a dynamic web page.

# A script which responds to http://example.com/search?q=cgi import cgi fs = cgi.FieldStorage () if'q' in fs: do_search () # An excerpt from cgi.py that explains how that works class FieldStorage:. . . Def _ _ contains__ (self, key): if self.list is None: raise TypeError ('not indexable') return any (item.name = = key for item in self.list) def _ _ len__ (self): return len (self.keys ()) once you have created an instance of the cgi.FieldStorage class, you can use the "in" operator to check whether a particular parameter is included in the query string.

And the _ _ contains__ () method is the protagonist who makes the magic work.

If the code is if'Q'in fs,Python, it looks for the _ _ contains__ () method in the fs object, which is already defined in cgi.py.' The value of Q'is passed into the _ _ contains__ () method as a key parameter.

The same FieldStorage class also supports returning its length, so you can write code len (fs) that calls the _ _ len__ () method of FieldStorage and returns the number of query parameters it recognizes.

The self.keys () method checks whether the self.list is None is true, so the _ _ len__ method does not need to repeat the error check.

Classes that behave like dictionaries

With a slight extension from the previous section, you can not only respond to the "in" operator and the len () function, but also return values based on keys like a full-featured dictionary.

Get the value x [key] x.substitutable gettemps _ (key) set the value x [key] = valuex.__setitem__ (key, value) by key to delete a key pair del x [key] x.invalid deliverables _ (key) provide the default value for the missing key x [nonexistent _ key] x.missing keys misplaced _ (nonexistent_key)

The FieldStorage class of the cgi module also defines these special methods, which means that they can be encoded as follows:

# A script which responds to http://example.com/search?q=cgi import cgi fs = cgi.FieldStorage () if'q' in fs: do_search (fs ['q']) # An excerpt from cgi.py that shows how it works class FieldStorage:. . .def _ getitem__ (self, key): if self.list is None: raise TypeError ('not indexable') found = [] for item in self.list: if item.name = = key: found.append (item) if not found: raise KeyError (key) if len (found) = = 1: return found [0] else: return found

The fs object is an instance of the cgi.FieldStorage class, but you can still evaluate the expression like fs ['q'].

Fs ['q'] calls the _ _ getitem__ () method by setting the key parameter to'q'. It then looks for a dictionary entry whose .name matches the given key in its internally maintained query parameter list (self.list).

Comparable class

I took this out of the previous section to make it a separate section because the "compare" operation is not limited to numbers. Many data types can be compared-strings, lists, even dictionaries. If you want to create your own class, and the comparison between objects is meaningful, you can use the following special methods to achieve the comparison.

Equal x = = yx.__eq__ (y) unequal x! = yx.__ne__ (y) less than x

< yx.__lt__(y)小于或等于x yx.__gt__(y)大于或等于x >

= yx.__ge__ (y) Truth values in the context of the Boolean context if x _ ()

If ☞ defines the _ _ lt__ () method but does not define the _ _ gt__ () method, Python will call the _ _ lt__ () method through the exchanged operator. However, Python does not combine methods. For example, if you define the _ _ lt__ () method and the _ _ eq () _ method, and try to test whether x

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