Python 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__':
{'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 '<--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 = -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 == '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 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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.
