Skip to content

Best Practices

raphaelreinauer edited this page May 16, 2022 · 5 revisions

Forwarding methods to members

from typing import Any


class C:
    def f(self):
        print("Hello from C")

class D:
    def __init__(self, c: C):
        print("Initializing D")
        self.c = c
        
    def g(self):
        print("Hello from D")
    
    # Forward the call of the function f to the object c
    def __getattr__(self, name: str) -> Any:
        return getattr(self.c, name)
        
c = C()
d = D(c)
d.f()
d.g()

# Output:
# Initializing D
# Hello from C
# Hello from D

getattr

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism, getattr() is not called. (This is an intentional asymmetry between getattr() and setattr().) This is done both for efficiency reasons and because otherwise getattr() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the getattribute() method below for a way to actually get total control in new-style classes.

https://docs.python.org/2.7/reference/datamodel.html#customizing-attribute-access

Clone this wiki locally