2015/9/29 Python Basics (20): Class authorization

Source: Internet
Author: User

Class of Authorization
1. Packaging
A term that is often mentioned when wrapping in the Python programming world. It is a generic name that means wrapping an existing object, whether it is a data type or a piece of code, that can be added to an existing object, add new, delete, or modify other existing functions.
Before Python2.2, the standard type subclasses or derived classes from Python are not allowed, and even if you can do this now, this is not a lot of practice. You can wrap any type as a core member of a class so that the behavior of the new object mimics the behavior that already exists in the data type you want, and removes the behavior that you do not want to exist; it may do something extra. This is the "package type". In the appendix, we will also discuss how to extend Python, another form of packaging.
Packaging includes defining a class whose instances have the core behavior of a standard type, but it is also improved through new or up-to-date functionality, and possibly even by different methods of accessing actual data.
Classes can also be packaged, but this is not much of a use, because there is already a mechanism for manipulating objects, and, as previously described, we use derivations to wrap them in a standard type.

2. Implementing authorization
Authorization is a feature of packaging that can be used to simplify the handling of dictating functionality and to maximize code reuse with existing functionality.
Wrapping a type is usually some customization of a type that already exists. As we mentioned earlier, this method can be used to create, modify, or delete the functionality of the original product. Others remain the same, or retain the existing functions and behaviors. The authorization process, that is, all the updated functionality is handled by a part of the new class, but the existing functionality is granted to the object's default property.
The key to implementing authorization is to overwrite the __getattr__ () method with a call to the GetAttr () built-in function in your code. Specifically, call GetAttr () to get the default object properties (data properties or methods) and return it for access or invocation. The Special Method __getattr__ () works by searching for a property, where any local object (a custom object) is first found. If the search fails, __getattr__ () is called. Then call GetAttr () to get the default behavior of an object.
That is, when referencing a property, the Python interpreter will try to find that name in the local namespace, such as a custom method or a local instance property. If not found in the local dictionary, the class namespace is searched in case A class property is accessed. Finally, if both types of searches fail, the search starts the authorization request on the original object, at which point the __getattr__ () is called.

A brief example of packaging objects
This class can wrap almost any object and provide basic functionality. For example, repr () and STR () are used to handle string notation, which is handled by the get () method, which removes the wrapper and returns the original object, so the reserved functionality is granted to the object's local property, which, if necessary, is __getattr__ () obtained.

>>>classWrapme (object):def __init__(self, obj): self.__data=objdefGet (self):returnSelf.__data    def __repr__(self):return' Self.__data'def __str__(self):returnSTR (self.__data)def __getattr__(self, attr):returnGetAttr (self.__data, attr)

We use the plural to give the first example, because complex numbers have data attributes and conjugate () built-in methods.

>>> Wrappedcomplex = WRAPME (3.3+1.2j)>>> Wrappedcomplex (3.3+1.2j)> >> wrappedcomplex.real3.3>>> wrappedcomplex.imag1.2>>>  Wrappedcomplex.conjugate ()(3.3-1.2j)>>> wrappedcomplex.get (3.3+1.2j)

Once we have created the wrapped object type, as long as the interaction interpreter calls REPR (), we can get a string representation, and then we access the three properties of the complex number, which is not defined in the class. Access to this property is granted to the object through the __getattr__ () method. The Get () method of the final call is not authorized because it is defined separately for our object.
Then there is an example of a list

>>> wrappedlist = WRAPME ([123,'Foo', 45.67])>>> Wrappedlist.append ('Bar')>>> Wrappedlist.append (123)>>>wrappedlist[123,'Foo', 45.67,'Bar', 123]>>> Wrappedlist.index (45.67)2>>> Wrappedlist.count (123)2>>>Wrappedlist.pop ()123>>>wrappedlist[123,'Foo', 45.67,'Bar']


Note that although we are using instances in our example, they show very similar behavior to the data types they wrap. Then you need to understand that only the existing attributes are authorized in this code.
But not all actions can be accessed, such as:

>>> wrappedlist[3"<pyshell#29>" in <module>  wrappedlist[3'wrapme' not support indexing

For the index slice operation of a list, it is built into the type, not as an attribute as the Append () method. So cannot be accessed. From another perspective, the slice operator is part of the sequence type and is not implemented by a special method such as __getitem__ ().
We have a "cheat" method that accesses the actual object and then uses its slicing ability:

>>> reallist = wrappedlist.get ()>>> reallist[3]'bar' 

That's why we implement the Get () method, where we can access the properties of the object directly from the access call, ignoring the local variables.
Here is an example of a simple wrapper class. We are also just beginning to touch the use of type emulation for class customization. You will find that you can make an unlimited number of improvements to further increase the use of your code.

Update a simple Package class
Creation time, modification time, and access time are several common properties of a file. We will add a time attribute to a class, the creation time (' CTime ') is the time of the instantiation, the modification time (' Mtime ') is the time of the core data upgrade, and the Access time (' Atime ') is the timestamp of the last time the object data value was fetched or the property was accessed.
We update the previously defined class, creating a module twrapme.py
The code is as follows:

 fromTimeImportTime , CTimeclassTimewrapme (object):def __init__(self, obj): self.__data=obj self.__ctime= self.__mtime=Self .__atime=Time ()defGet (self): self.__atime=Time ()returnSelf.__data    defgettimeval (Self, t_type):if  notIsinstance (T_type, str)orT_type[0] not inch 'CMA':            RaiseTypeError,"argument of ' C ', ' m ', or ' a ' req ' d"        returnGetAttr (Self,'_%s__%stime'%(self. )__class__.__name__, t_type[0])) defgettimestr (Self, t_type):returnCTime (Self.gettimeval (t_type))defset (self, obj): self.__data=obj self.__mtime= Self.atime =Time ()def __repr__(self): self.__atime=Time ()return' Self.__data`    def __str__(self): self.__atime=Time ()returnSTR (self.__data)    def __getattr__(self, attr): Self.__atime=Time ()returnGetAttr (self.__data, attr)

The test is as follows:

>>> timewrappedobj = TIMEWRAPME (123)>>> Timewrappedobj.gettimestr ('C')'Tue Sep 17:25:11'>>> Timewrappedobj.gettimestr ('m')'Tue Sep 17:25:11'>>> Timewrappedobj.gettimestr ('a')'Tue Sep 17:25:11'>>>Timewrappedobj123>>> Timewrappedobj.gettimestr ('C')'Tue Sep 17:25:11'>>> Timewrappedobj.gettimestr ('m')'Tue Sep 17:25:11'>>> Timewrappedobj.gettimestr ('a')'Tue Sep 17:25:26'>>> Timewrappedobj.set ('Update time!')>>> Timewrappedobj.gettimestr ('m')'Tue Sep 17:28:06'>>>Timewrappedobj'Update time!'>>> Timewrappedobj.gettimestr ('C')'Tue Sep 17:25:11'>>> Timewrappedobj.gettimestr ('m')'Tue Sep 17:28:06'>>> Timewrappedobj.gettimestr ('a')'Tue Sep 17:28:19'

2015/9/29 Python Basics (20): Class authorization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.