search
HomeBackend DevelopmentPython TutorialPython Advanced __attr__ Object Attribute

Everything in Python is an object, and each object may have multiple attributes. Python's attributes have a unified management scheme.

The attributes of an object may come from its class definition, which is called a class attribute.

Class attributes may come from the class definition itself, or they may be inherited from the class definition.

The attributes of an object may also be defined by the object instance, which are called object attributes.

The properties of an object are stored in the __dict__ attribute of the object.

__dict__ is a dictionary, the key is the attribute name, and the corresponding value is the attribute itself. Let's look at the classes and objects below.

Corresponds to Java's reflection to obtain the attributes of the object, such as:

public class UserBean {
    private Integer id;
    private int age;
    private String name;
    private String address;
}
//类实例化
UserBean bean = new UserBean();
bean.setId(100);
bean.setAddress("武汉");
//得到类对象
Class userCla = (Class) bean.getClass();
      
//得到类中的所有属性集合
Field[] fs = userCla.getDeclaredFields();
......
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__)

Output:

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

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

{'age': 2}

The first line is the attribute of the bird class, such as feather.

The second line is the attributes of the chicken class, such as fly and __init__ methods.

The third line is the attribute of the summer object, which 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 the object class (just like our bird definition, class bird(object)). This object class is the parent class of all classes in Python.

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

You can modify the properties of a class through the following 2 methods:

summer.__dict__['age'] = 3
print(summer.__dict__['age'])
summer.age = 5
print(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 change at the same time. At this time, we cannot statically store attributes through __dict__. Python provides several ways to generate properties on the fly. One of them is called a property.

class bird(object):
    feather = True
#extends bird class
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)

The functionality here is similar to a trigger. Every time the adult attribute is obtained, the value of getAdult will be triggered.

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

class num(object):
    def __init__(self, value):
self.value = value
print &#39;<--init&#39;
    def getNeg(self):
print &#39;<--getNeg&#39;
return self.value * -1
    def setNeg(self, value):
print &#39;<--setNeg&#39;
self.value = (-1) * value
    def delNeg(self):
print("value also deleted")
del self.value
    neg = property(getNeg, setNeg, delNeg, "I&#39;m negative")
x = num(1.1)
print(x.neg)
x.neg = -22
print(x.value)
print(num.neg.__doc__)
del x.neg

During the entire process, the corresponding functions were not called.

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

Python special method __getattr__ (this is commonly used)

We can use __getattr__(self, name) to query the attributes generated on-the-fly.

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

Then the function of getattr is to perform a layer of judgment processing when generating these attributes.

For example:

class bird(object):
    feather = True
class chicken(bird):
    fly = False
    def __init__(self, age):
self.age = age
    def __getattr__(self, name):
if name == &#39;adult&#39;:
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 processing function, and __getattr__ can handle all instant generated attributes in the same function. __getattr__ can handle different attributes based on the function name. For example, when we query the attribute name male above, we raise AttributeError.

(There is also a __getattribute__ special method in Python, which is used to query any attribute.

__getattr__ can only be used to query attributes that are 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 range of applications and can be used for any attribute.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment