Python advanced _ attr _ object attributes

Source: Internet
Author: User
In Python, everything is an object. each object can have multiple attributes ). Python attributes have a set of unified management solutions. The attributes of an object may come from its class definition, which is called a class attribute. (the class attributes are all objects.) each object may have multiple attributes ). Python attributes have a set of unified management solutions.

The attribute of an object may come from its class definition, called class attribute ).

Class attributes may come from the class definition itself or inherit from the class definition.

The attribute of an object may also be defined by the object instance, which is called the object attribute ).

The object attributes are stored in the _ dict _ attribute of the object.

_ Dict _ is a dictionary with the key as the property name and the corresponding value as the property itself. Let's look at the following classes and objects.

Corresponding to Java reflection, to get the object attributes, such:

Public class UserBean {private Integer id; private int age; private String name; private String address;} // class instantiation UserBean bean = new UserBean (); bean. setId (100); bean. setAddress ("Wuhan"); // you can obtain the Class object Class userlinoleic = (Class) bean. getClass (); // obtain all the attribute sets in the class Field [] fs = userlinoleic. 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 _':, '_ module _': '_ main _', '_ weakref _':, 'feate ': true, '_ doc _': None}

{'Fly ': False,' _ module _ ':' _ main _ ',' _ doc _ ': None, '_ init __': }

{'Age': 2}

The first behavior is the attributes of the bird class, such as feather.

The second behavior is the attributes of the chicken class, such as the fly and _ init _ methods.

The third behavior is the property of the summer object, that is, age.

Some attributes, such as _ doc __, are not defined by us, but are automatically generated by Python. In addition, the bird class also has a parent class, which is an object class (as defined in bird, class bird (object )). This object class is the parent class of all classes in Python.

That is, the attributes of the subclass will overwrite the attributes of the parent class.

You can use the following two methods to modify the attributes of a class:

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

Property in Python

Different attributes of the same object may have dependencies. When an attribute is modified, we want other attributes of this attribute to change at the same time. In this case, we cannot use _ dict _ to store static attributes. Python provides multiple methods for generating attributes in real time. One of them is called a property ).

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 = property(getAdult)   # property is built-insummer = chicken(2)print(summer.adult)summer.age = 0.5print(summer.adult)

The functions here are similar to triggers. The getAdult value is triggered each time the adult attribute is obtained.

Features are created using the built-in function property. Property () can load up to four parameters. The first three parameters are functions used to process query features, modify features, and delete features. The last parameter is a feature document, which can be a string that describes the function.

class num(object):    def __init__(self, value):self.value = valueprint '<--init'    def getNeg(self):print '<--getNeg'return self.value * -1    def setNeg(self, value):print '<--setNeg'self.value = (-1) * 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

No corresponding functions are called throughout the process.

That is to say, the creation, setting, and deletion of the neg property are all registered through property.

Special Python method _ getattr _ (this is commonly used)

We can use _ getattr _ (self, name) to query the instantly generated attributes.

In pyhton, object attributes are dynamic and can be added or deleted as needed at any time.

The role of getattr is to perform a layer of judgment and processing operations when these attributes are generated.

For example:

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 AttributeError(name)summer = chicken(2)print(summer.adult)summer.age = 0.5print(summer.adult)print(summer.male)

Each feature requires its own processing function, and _ getattr _ can put all the instantly generated attributes in the same function for processing. _ Getattr _ different attributes can be processed according to the function name difference. For example, raise AttributeError occurs when we query the attribute name male.

(There is also a special _ getattribute _ method in Python to query any attribute.

_ Getattr _ can only be used to query attributes not in the _ dict _ system)

_ Setattr _ (self, name, value) and _ delattr _ (self, name) can be used to modify and delete attributes.

They have a wider application scope and can be used for any attribute.

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.