Properties of the object that Python learns deeply

Source: Internet
Author: User
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.

The code is as follows:


Class Bird (object):
Feather = True

Class Chicken (bird):
Fly = False
def __init__ (self, Age):
Self.age = Age

Summer = Chicken (2)

Print (bird.__dict__)
Print (chicken.__dict__)
Print (summer.__dict__)


Here is our output:

The code is as follows:


{' __dict__ ':, ' __module__ ': ' __main__ ', ' __weakref__ ':, ' feather ': True, ' __doc__ ': None}


{' Fly ': False, ' __module__ ': ' __main__ ', ' __doc__ ': None, ' __init__ ': }


{' 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:

The code is as follows:


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

Summer.age = 5
Print (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)

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:

The code is as follows:


Class Bird (object):
Feather = True

Class 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) # property is built-in

Summer = Chicken (2)

Print (Summer.adult)
Summer.age = 0.5
Print (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:

The code is as follows:


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 =-22
Print (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:

The code is as follows:


Class Bird (object):
Feather = True

Class 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
Else:raise Attributeerror (name)

Summer = Chicken (2)

Print (Summer.adult)
Summer.age = 0.5
Print (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.

  • 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.