Python--Properties of an object

Source: Internet
Author: User
Tags class definition

Transferred from: http://www.cnblogs.com/vamei/archive/2012/12/11/2772448.html

Python is all objects (object), and each object may have multiple properties (attribute). The properties of Python have a unified management scheme.

Properties of the __DICT__ system

The properties of an object may come from its class definition, called Class attribute. Class properties may come from the class definition itself, or it may be inherited from a class definition. The properties of an object may also be defined by the object instance, called the object attribute.

The properties of the object are stored in the __dict__ property of the object. __dict__ is a dictionary, the key is the property name, and the corresponding value is the property itself. Let's look at the following classes and objects. The chicken class inherits from the Bird class, and summer is an object of the chicken class.

Class Bird (object):    feather = Trueclass Chicken (bird):    fly = False    def __init__ (self, Age):        self.age = Agesummer = Chicken (2) print (bird.__dict__) print (chicken.__dict__) print (summer.__dict__)

Here is our output:

{' __dict__ ': <attribute ' __dict__ ' of ' bird ' objects>, ' __module__ ': ' __main__ ', ' __weakref__ ': <attribute ' __ weakref__ ' of ' bird ' objects>, ' feather ': True, ' __doc__ ': none}{' Fly ': False, ' __module__ ': ' __main__ ', ' __doc__ ': Non E, ' __init__ ': <function __init__ at 0x2b91db476d70>}{' age ': 2}

The first behavior is a property of the bird class, such as feather. The second behavior is the properties of the chicken class, such as the Fly and __init__ methods. The third behavior is the property of the summer object, which is age. Some properties, such as __doc__, are not defined by us, but are generated automatically by Python. In addition, the bird class also has a parent class, which is the object class (as in our bird definition, class bird (object)). This object class is the parent class for all classes in Python.

As you can see, the properties in Python are defined hierarchically, such as the four layers of object/bird/chicken/summer. When we need to invoke a property, Python walks up one layer at a time until the property is found. (a property may appear again different layers are repeatedly defined, Python up the process, will pick the first encountered, that is, the lower-level attribute definition).

When we have a summer object, we can query the properties of summer object, Chicken class, Bird class, and object class, and we will know all summer of __dict__ object. You can find all the properties that can be invoked and modified through the object summer. The following two property modification methods are equivalent:

Summer.__dict__[' age '] = 3print (summer.__dict__[' age ') Summer.age = 5print (summer.age)

(In the above case, we already know that the class of the summer object is chicken, and the parent class of the chicken class is bird.) If there is only one object, without knowing its class and other information, we can use the __class__ property to find the object's class, and then call the class's __base__ property to query the parent class)

Print Summer.__class__.__base__.feather

Output: True

Characteristics

There may be dependencies between different properties of the same object. When a property is modified, we want other properties that depend on that property to also change. At this point, we cannot store properties statically by __dict__. Python provides a variety of methods for generating properties on the fly. One of these is called an attribute. Attributes are special properties. For example, we add a feature adult to the chicken class. Adult is true when the object's age exceeds 1 o'clock, otherwise false:

Class Bird (object):    feather = Trueclass Chicken (bird):    fly = False    def __init__ (self, Age):        self.age = Age    def getadult (self):        if self.age > 1.0:return True        else:return False    Adult = property (Getadult) c8/># property is Built-insummer = Chicken (2) print (summer.adult) summer.age = 0.5print (Summer.adult)

Attributes are created using the built-in function property (). A property () can load up to four parameters. The first three parameters are functions, which are used to process query attributes, modify attributes, and delete attributes. The last parameter is an attribute of the document, which can be used as a string to illustrate the function.

We use one of the following examples to further illustrate:

Class num (object):    def __init__ (self, value):        self.value = value    def getneg (self):        return-self.value    def setneg (self, value):        self.value =-value    def delneg (self):        print ("Value also deleted")        del Self.value    neg = property (Getneg, Setneg, Delneg, "I ' M negative") x = num (1.1) print (X.NEG) X.neg = -22print (x.value) Print (num.neg.__doc__) del X.neg

The above num is a number, and neg is an attribute that is used to denote a negative number of numbers. When a number is determined, its negative numbers are always determined, and when we modify a negative number, the value itself should change. These two points are implemented by Getneg and Setneg. Delneg, however, is that if you delete an attribute neg, the action you should take is to delete the property value. The last parameter ("I ' M negative") of the property () is the description document for the attribute negative.

Using special methods __getattr__

We can use __getattr__ (self, name) to query the properties of an instant build. When we query a property, if the property cannot be found through the __dict__ method, Python invokes the object's __getattr__ method to generate the property on the fly. Like what:

Class Bird (object):    feather = Trueclass Chicken (bird):    fly = False    def __init__ (self, Age):        self.age = Age    def __getattr__ (self, name):        if name = = ' Adult ':            if self.age > 1.0:return True            else:return false< C8/>else:raise attributeerror (name) Summer = Chicken (2) print (summer.adult) summer.age = 0.5print (summer.adult) print ( Summer.male)

Each feature needs its own handler, and __getattr__ can handle all of the immediate generation properties in the same function. __GETATTR__ can handle different properties depending on the function name. For example, when we query the property name male, raise Attributeerror.

(Python also has a __getattribute__ special method for querying any property.) __GETATTR__ can only be used to query properties that are not in the __dict__ system)

__setattr__ (self, name, value) and __delattr__ (self, name) can be used to modify and delete properties. They have a wider application and can be used for any attribute.

Other ways to generate properties on the fly

The immediate generation of properties can also be used in other ways, such as descriptor (the descriptor class is actually the bottom of the property () function, which actually creates an object of that class). Interested can be further consulted.

Summarize

__dict__ Tiered Storage properties. The __dict__ of each layer only stores the new properties of the layer. Subclasses do not need to store properties in the parent class repeatedly.

Generating properties on the fly is a concept worth knowing. In Python development, you might use this method to manage the properties of objects more rationally.

Python--Properties of an object

Related Article

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.