Python Advanced __attr__ Object Properties

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.

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.

Corresponding to the reflection in Java, to get the properties of the object, such as:

public class UserBean {    private Integer ID;    private int age;    private String name;    Private String address;} Class instantiation UserBean bean = new UserBean (); Bean.setid (+); Bean.setaddress ("Wuhan");//Get Class object class Usercla = (Class) Bean.getclass ();      Get all the attributes in the Class collection field[] fs = Usercla.getdeclaredfields ();
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__)

Output:

{' __dict__ ': <attribute ' __dict__ ' of ' bird ' objects>, ' __module__ ': ' __main__ ', ' __weakref__ ': <attribute ' __ weakref__ ' of ' bird ' objects>, ' feather ': True, ' __doc__ ': None}

{' Fly ': False, ' __module__ ': ' __main__ ', ' __doc__ ': None, ' __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.

That is, the property of the child class that overrides the parent class's properties.

The properties of the class can be modified by the following 2 Chinese laws:

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

Property in Python

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.

Class Bird (object):    feather = true#extends Bird Classclass 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 = Pro Perty (Getadult)   # property is Built-insummer = Chicken (2) print (summer.adult) summer.age = 0.5print (Summer.adult)

The function here is similar to a trigger. The value of Getadult is triggered each time the adult property is fetched.

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.

Class num (object):    def __init__ (self, value): Self.value = Valueprint ' <--init '    def getneg (self):p rint ' < --getneg ' Return Self.value *-1    def setneg (self, value):p rint ' <--setneg ' Self.value = ( -1) * Value    def delneg ( Self):p rint ("value also deleted") del self.value    neg = property (Getneg, Setneg, Delneg, "I ' M negative") x = num (1.1) PRI NT (X.NEG) X.neg = -22print (x.value) print (num.neg.__doc__) del X.neg

The corresponding functions are not called in the whole process.

In other words, the creation, setting, and deletion of the Neg attribute are registered through the property ().

Python Special Method __getattr__ (this common)

We can use __getattr__ (self, name) to query the properties of an instant build.

In Pyhton, object properties are dynamic, and you can add or remove properties as needed at any time.

Then the GetAttr function is to perform a layer of judgment processing when these attributes are generated.

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 trueelse:return falseelse:raise attributee Rror (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.

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