


Compare the usage of __getattr__ and __getattribute__ to obtain attributes in Python
I believe that most of the time we don’t need to pay much attention to the details of getattribute and getattr (at least myself:)),
Under normal circumstances, when consuming our custom classes, we understand the structure of the class and will not deliberately deviate and cause some attribute access errors.
But as a curious, pursuing and temperamental Python baby, how could I not do a little research? Well, I actually read the source code of sinaweibopy, an open source project on github. The code is quite interesting and can be used as a practical example to see how to customize gettattr to make the code more dynamic and elegant:
# 例子在原来的基础上简化了一下,排除依赖和干扰,详细参见原项目 class UrlGenerator(object): def __init__(self, root_url): self.url = root_url def __getattr__(self, item): if item == 'get' or item == 'post': print self.url return UrlGenerator('{}/{}'.format(self.url, item)) url_gen = UrlGenerator('http://xxxx') url_gen.users.show.get >>> http://xxxx/users/show
Make full use of the feature that getattr will be called when the corresponding instance attribute is not found, and conveniently generate the corresponding URL through chain calls. When the http method is encountered in the source code, a
is returned.
Callable objects are more elegant, and chained operations are not only elegant but also well explain the meaning of the called interface (restful interface).
Example
1.__getattr__ example:
class Test(object): def __init__(self,name): self.name = name def __getattr__(self, value): if value == 'address': return 'China' if __name__=="__main__": test = Test('letian') print test.name print test.address test.address = 'Anhui' print test.address
Run result:
letian China Anhui
If an undefined method in a class is called, __getattr__ will also return a method, for example:
class Test(object): def __init__(self,name): self.name = name def __getattr__(self, value): return len if __name__=="__main__": test = Test('letian') print test.getlength('letian')
Run result:
6
2.__getattribute__ example:
class Test(object): def __init__(self,name): self.name = name def __getattribute__(self, value): if value == 'address': return 'China' if __name__=="__main__": test = Test('letian') print test.name print test.address test.address = 'Anhui' print test.address
Run result:
None China China
Think deeply
Since some elegant functions can be realized through the getattr custom method of the custom class, naturally we also need to have some understanding of it, including its similar custom method getattribute
1. Used as acquisition and interception of instance attributes
When accessing an instance attribute, getattribute will be called unconditionally. If your own getattr method is not implemented, an AttributeError will be thrown to prompt that the attribute cannot be found. If you have customized your own getattr method, the method will be in this way. Called when the property cannot be found, such as in the example above. So it is a good way to implement some functions by implementing a custom getattr method when the attribute cannot be found, because it will not be called every time like the getattribute method, which may affect some normal attribute access:
class Test(object): def __init__(self, p): self.p = p def __getattr__(self, item): return 'default' t = Test('p1') print t.p print t.p2 >>> p1 >>> default
2. Prevent infinite recursion when customizing getattribute
Because getattribute will always be called when accessing attributes, the custom getattribute method needs to return the corresponding attribute at the same time. Taking the value through self.__dict__ will continue to call getattribute downwards, causing a circular call:
class AboutAttr(object): def __init__(self, name): self.name = name def __getattribute__(self, item): try: return super(AboutAttr, self).__getattribute__(item) except KeyError: return 'default'
Here, the attributes of the formation are obtained by calling the bound super object. For new-style classes, it is actually the same as object.__getattribute__(self, item):
By default, customized classes will inherit the getattribute method from object, and attribute search is fully usable
The implementation of getattribute feels quite abstract. You only need to bind the corresponding instance object and the name of the attribute you want to find
3. When overriding getattribute and getattr at the same time, you need to imitate the original behavior and throw AttributeError in getattribute or manually call getattr
class AboutAttr(object): def __init__(self, name): self.name = name def __getattribute__(self, item): try: return super(AboutAttr, self).__getattribute__(item) except KeyError: return 'default' except AttributeError as ex: print ex def __getattr__(self, item): return 'default' at = AboutAttr('test') print at.name print at.not_exised >>>test >>>'AboutAttr' object has no attribute 'not_exised' >>>None
The getattr method in the above example will not be called at all, because the original AttributeError was handled by ourselves and was not thrown, and getattr was not called manually, so the result of accessing not_existed is None instead of default.

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

AI Hentai Generator
Generate AI Hentai for free.

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

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid
