Home > front end >  How to correct attribute error while working with two methods in a python class?
How to correct attribute error while working with two methods in a python class?

Time:07-13

I have a class defined as below;

class A:
    def __init__(self) ->None:
        pass
    
    def method_A(self,d,m):
        self.DATOS = d
        self._METH = m
        
    def method_B(self):
        return self.DATOS

I have instantiated A class as follow and trying to call a method_B from it

x = A()
x.method_B()

here it throws an error as:

AttributeError: 'A' object has no attribute 'self.DATOS'

How to pass an attribute from method A to method B ? without defining them in init?

CodePudding user response:

So, for the attribute DATOS to exist you must call the method_A first. Your A instance doesn't know about DATOS until you call method_A. In that method you declare the variable and give it a value, after that you will be able to access it.

CodePudding user response:

If you want to do that without defining attribute in __init__ you might try getattr() function:

class A:
    def __init__(self) ->None:
        pass
    
    def method_A(self,d,m):
        self.DATOS = d
        self._METH = m
        
    def method_B(self):
        return getattr(self, 'DATOS', None) # check if DATOS is defined and return it value otherwise return None
  • Related