1

python class module __getattr__ use funation obj.val1.val2 error. python program for.

class hub:
    def __getattr__(self,__name):
        print(__name)

obj = hub()
obj.val1.val2

error:

val1
Traceback (most recent call last):
  File "hub.py", line 6, in <module>
    obj.val1.val2
AttributeError: 'NoneType' object has no attribute 'val2'

Expert Value:

val1.val2
THAVASI.T
  • 131
  • 1
  • 5

2 Answers2

1

The attribute obj.val1 is none. When you use obj.val1.val2 it actually calls the getattr of obj.val1 which is none. Because obj.val1 is none and doesn't have a val2 attribute you receive an error.

sputnick567
  • 324
  • 5
  • 12
0

you are not returning anything which is equivalent to returning None and then you are trying to get another attribute from none which fails.

this code should works if you are just trying to print the values:

class hub:
    def __getattr__(self,__name):
        print(__name)
        return self

obj = hub()
obj.val1.val2

otherwise if you are trying to get a tuple of value you are trying to do it the wrong way it will not work with __getattr__ directly. use __getitem__ first

class hub:
    def __getitem__(self, *keys):
        return [self.__getattr__(k) for k in keys]

    def __getattr__(self,__name):
        # get the item here and return it

obj = hub()
obj["val1", "val2"]
LTBS46
  • 205
  • 1
  • 10