Hướng dẫn python getattr child class
I have a class who's fields are an instance of another class. Show
What I'd like to be able to do is when an instance of the parent refers to its attributes, instead it calls the child's methods.
The other catch is that I only want this behavior when the field is of type I'm running into recursion problems try to use
The recursion is fairly obvious why its happening... but how do I avoid it? I've seen a few examples already on StackOverflow, but I can't seem to figure out how to get around it.
Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.
How getattr() works in PythonExample 1: Demonstrating working of getattr()Python3
Output: The name is GeeksforGeeks Description is CS Portal Exception: AttributeError: GfG instance has no attribute 'motto' Example 2: getattr() when named attribute is not foundPython3
Output: AttributeError: 'GfG' object has no attribute 'gender' Example 3: Performance Analysis and getattr python with parameterPython3
Output: The name is GeeksforGeeks Time to execute getattr 5.0067901611328125e-06 The name is GeeksforGeeks Time to execute conventional method 1.1920928955078125e-06 Example 4: getattr Python default valuePython3
Output: AttributeError: 'GfG' object has no attribute 'motto' Example 5: Python getattr() function callPython3
Output: <__main__.GfG object at 0x0000023C1ED92748> Result : Conventional method takes less time than getattr(), but when default values have to be used in case of missing attributes, getattr() is a good choice. Applications: The are many applications of getattr(), a few of them already mentioned in cases of absence of attributes of objects, in web developments where some of the form attributes are optional. Also useful in cases of Machine Learning feature collections in case some features sometimes go missing in data collection. |