Created
February 7, 2019 10:39
-
-
Save mocquin/28e0fa990fb3d2794fa6dfc487b33558 to your computer and use it in GitHub Desktop.
Example of __getattr__ magic method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""See https://stackoverflow.com/questions/3278077/difference-between-getattr-v | |
s-getattribute : | |
__getattr__ is only invoked if the attribute wasn't found the usual ways. | |
It's good for implementing a fallback for missing attributes, and is probab | |
ly the one of two you want. | |
""" | |
import numpy as np | |
class foo(): | |
def __init__(self,array): | |
self.array = array | |
class bar(): | |
def __init__(self,array): | |
self.array = array | |
def __getattr__(self,name): | |
return self.array.__getattribute__(name) | |
my_foo = foo(np.array([1])) | |
my_bar = bar(np.array([1,2,3,4,5,6,7,8,9,10])) | |
try: | |
print(my_foo.shape) # AttributeError : 'foo' object has no attribute 'shape' | |
except: | |
print(my_bar.shape) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment