Python: A brief discussion of properties in Python

Source: Internet
Author: User

Origin:
The project process needs to study YOUTUBE_DL this open source component, through the use of the class, compared to C # and Delphi implementation, feel the Python property mechanism is very interesting.
The distinction and the single entrance of the high-level programming language, in the nature of the class, it is so arbitrary that it is so accustomed to the rigor of the high-level language that it is somewhat uneasy in such a casual mind.
No wonder, because its data type is weak and restrictive, often a function returns a result that traces the return value type, sometimes it takes a lot of work!
I'm not a random person, but I'm not a human being, and it's quite appropriate to use it here: b

attribute is an abstraction of a property, an important concept in object-oriented programming, and is distinguished from a field, which is usually represented as an extension of a field, accessed and set up to protect the mechanism.
For example, the animal, its color, weight, can be said to be its properties, this article with an animal class to do an example, shallow probe into the properties of the mechanism.

1. New class and Classic Class (New-style classes)

Python 2.x default class for the classic class, and the property support is completely new class, the difference please self-niang.
Python 3.x is a modern class by default and does not have to be explicitly inherited from the object class.
As defined in the following code class:

# This is the classic class class animalclassic:     Pass # This is a new class, Python 2.2 supports class Animal (object):     Pass

Although an object is different, its intrinsic mechanism has changed a lot. A glimpse of it, broadly as follows:

>>>print dir (animalclassic)

Return:

['__doc__'__module__']

>>>print dir (Animal)

Return:

['__class__','__delattr__','__dict__','__doc__','__format__','__getattribute__','__hash__','__init__','__module__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__']

So, it joins many object-oriented support, this section attribute knowledge, also constructs based on the modern class. So gentlemen use Python 2.x to develop, write object-oriented code, remember to inherit from the object class

2. Random attributes

In general, we define properties like this:

class Animal (object):     def __init__ (self, Name, age):         = name        = Age

That is, when the instance is initialized, the __INIT__ function is assigned a value, where the value can be accessed by the instance:

A = Animal ('black dog', 3)print'Name:'  , A.nameprint'age:'Black'  print'Color:', A.color

The result is:

3color:black

Did you see that? runtime, you can dynamically add properties to the instance, such as color. However, this method adds only to this instance, without affecting the class
How to limit it? With __slots__ this thing, for example, __slots__ = [' name ', ' age '], then the class can only add these two properties, the egg hurts, not useful
If you want to add a property to a class at run time, use the Methodtype, for example:

def Set_color (self, color):      = = = Animal (' Yellow Dog ', 3) a1.set_color ('  Yellow')print A1.color

...... Oh, a bit messy, or not good use! Or, the heart is not some numbers.


3. @property

Accustomed to the rigor of high-level language, always want to access control of attributes, relatively safe, such as directly in the __init__ definition of common properties, from the encapsulation, it is not a bad writing.
Property access, it also has a mechanism, one of which is the @propery keyword. With this keyword, its get, set function, must be consistent with the property name.
@property can turn an instance method into a property of the same name to support the. Number access, which also flags the set limit and is normalized with the following code:

classAnimal (object):def __init__(self, Name, age): Self._name=name Self._age=Age Self._color='Black'@propertydefname (self):returnself._name @name. Setterdefname (self, value):ifisinstance (value, basestring): Self._name=valueElse: Self._name='No name'@propertydefAge (self):returnself._age @age. SetterdefAge (self, value):ifValue > 0 andValue < 100: Self._age=valueElse: Self._age=0#print ' Invalid age value. '@propertydefColor (self):returnself._color @color. SetterdefColor (self, value): Self._color=value; A= Animal ('Black Dog', 3) A.name='White Dog'A.age= 300Print 'Name:', A.namePrint 'Age :', A.age

So at the time of setting the value, finally have a judgment choice, is not better?
The private variable begins with _, is a coded write, and of course it can be accessed directly.
However, direct access is not recommended.
If you really want to be a private variable, then add double underscore, such as __name, also can not prevent access, but let us know that it does not want to be used directly, the following code:

class Animal (object):     def __init__ (self, name): Self        . __name == Animal ('black dog')print a._ Animal__name

This kind of writing is really curious!
Liu Xuefeng: In general, Python itself has no mechanism to prevent you from doing bad things, all by self-consciousness.

4. Property function
It defines a property in the form of a function, similar to the @property implementation principle, or its variant usage.
The prototype is:

Property (Fget=none, Fset=none, Fdel=none, Doc=none)

For example, the above animal class, which can be changed to:

classAnimal (object):def __init__(self, Name, age): Self._name=name Self._age=Age Self._color='Black'    defget_name (self):returnSelf._namedefset_name (self, value):ifisinstance (value, basestring): Self._name=valueElse: Self._name='No name'name= Property (Fget=get_name, Fset=set_name, Fdel=none, doc='name of an animal')    defget_age (self):returnSelf._agedefset_age (self, value):ifValue > 0 andValue < 100: Self._age=valueElse: Self._age=0#print ' Invalid age value. ' Age= Property (Fget=get_age, Fset=set_age, Fdel=none, doc='name of an animal') A= Animal ('Black Dog', 3) A.name='White Dog'A.age= 3Print 'Name:', A.namePrintAnimal.name.__doc__Print 'Age :', A.age

Its output, it seems, is just different.

Postscript:
This shows that python, as an interpreted language, is easy to use, but its randomness is also large. This attribute is only one of the points, and other aspects must be learned in the use of attention.
Accustomed to grammar rigorous, coding also please pythonic style to write, Python is not much limit, as long as the correct computer can compile, code style is for people to see, elegant is better than messy.

As the above several attributes, I especially like @property way, relatively concise some

Resources:

Built-in Functions
Python Basics: Property access for modern classes
Python Deep properties for 03 objects

Python: A brief discussion of properties in Python

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.