In Python, use descriptor to implement class-level attributes (property) detailed _python

Source: Internet
Author: User

The previous article briefly introduces the concept and use of the Python Descriptor (descriptor), which is estimated to have get√ the skill. This article through a descriptor use scene again to give a case, let the students do not understand the situation can be easier to understand.

Let's talk about decorator.

These two words are indeed somewhat similar, and they are inseparable in their use. This also caused the understanding of the difficulties, said the adorner and the descriptor, why is it necessary to use a @ symbol plus the descriptor to do.

A lot of articles also put these two together, I will feel very around after reading. In fact, learning a knowledge point, and do project development a function is the same. When the function splits, we try to split the task small enough before assigning it to the developer. This ensures the independence, completeness, and ease of progress management of each task. It is not possible to put your tasks into a function/interface during the development of a task to avoid high coupling between functions, which can be difficult to maintain later.

And go back to learning a technical point, if you always try to master two or more technical points, the result may be busy for a long time, found or disoriented.

Rub, it seems to pull away.

Said descriptor is descriptor, decorator is decorator, encounter not understand place, broken, where do not know where. So first say decorator, the key point is that you have to realize that this is a grammatical sugar. The so-called grammatical sugar is so that you can write the code in a simple way. In essence the adorner (decorator) is like this:

Copy Code code as follows:

def decorator (func):
def wrapper ():
print ' in decorator '
Func ()
Return wrapper

def func ():
print ' in Func '

# Decorate the Func
Func = Decorator (func) # The Func on the left is actually the wrapper, you execute it, it will help you execute func ()
# equals you when you define Func @
@decorator
def func ():
print ' in Func '

Topic: To make a class-level property by descriptor

The common property is this:

Copy Code code as follows:

Class Foo (object):
_name = ' The5fire '

@property
def name (self):
Return Self._name

The use of this property is an instance-level application. Because only after foo = foo (), you can foo.name.

But what if I need a class-level attribute, like Classmethod, I can call without instantiating the class. The corresponding requirement is such that a base class dbmanage is defined:

Copy Code code as follows:

Class Dbmanage (object):
@classmethod
DEF table_name (CLS):
Return Cls.__name__.lower ()

@classmethod
def select_all (CLS):
sql = "SELECT * from%s" "% Cls.table_name ()
# code to execute this statement
return result

This is actually an underlying model that corresponds to a table in the database, and I want the other models to inherit it, and then reuse the TABLE_NAME method (now or the method).

All I need to do is define the user model:

Copy Code code as follows:

Class User (Dbmanage):
Pass

Then this defines the post model:
Copy Code code as follows:

Class Post (Dbmanage):
Pass

So if I need to check all the User data, I just need to User.select_all (), and the same Post is Post.select_all (). But at this point found a little uncomfortable things. That's the code for the Cls.table_name () in the base class, TABLE_NAME looks like a property, but it needs to be fetched by invoking the method. Wrong.

Then a classproperty was defined:

Copy Code code as follows:

Class Classproperty (object):
def __init__ (Self, func):
Self.func = Func

def __get__ (self, instance, Klass):
Return Self.func (Klass)

This requires that my code in Dbmanage can be changed to:

Copy Code code as follows:

Class Dbmanage (object):
@classproperty
DEF table_name (CLS):
Return Cls.__name__.lower ()

@classmethod
def select_all (CLS):
sql = "SELECT * from%s" "% Cls.table_name # how Intuitive


This is another use case for descriptor.
There may be someone or there is a little doubt: for Mao you are not directly sql = "SELECT * from%s"% cls.__name__.lower () in SQL assignment. This question, ask very good, the reason is one word: lazy. Too lazy to knock so much code every time.

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.