Home > Net >  AttributeError: 'obj_2' object has no attribute 'var_1' - getattr -
AttributeError: 'obj_2' object has no attribute 'var_1' - getattr -

Time:07-26

I need to get data to second class from first class. I Used - getattr - function to do it.

class obj_1:
    def __init__(self):
        self.var_1 = 'Hello'
        self.var_2 = 'World'


    def get_id(self):
        i = self.var_1
        j = self.var_2       
        return i, j

    def vw(self):
        print('Hello..')

class obj_2:
    def __init__(self):
        pass


    def r_data(self):
        print('called r_data')
        x, y = getattr(obj_1, "get_id")(self)

        print('x > ', x)
        print('y > ', y)

    def rd(self):
        getattr(obj_1, 'vw')(self)

if __name__ == '__main__':
    ob = obj_2()
    ob.r_data()

It given error as - AttributeError: 'obj_2' object has no attribute 'var_1'

CodePudding user response:

I think you are getting this error since the function get_id uses attributes of the class, i.e self.var_1 self.var_2

and these attributes are never initialized since the __init__ function was never called (and since you cant have attributes without an actual object )

so to fix your code I would create an object of "obj_1" and call the function "get_id" with that object

class obj_1:
    def __init__(self):
        self.var_1 = 'Hello'
        self.var_2 = 'World'


    def get_id(self):
        i = self.var_1
        j = self.var_2
        return i, j

    def vw(self):
        print('Hello..')

class obj_2:
    def __init__(self):
        self.o1 = obj_1()


    def r_data(self):
        print('called r_data')
        x, y = self.o1.get_id()

        print('x > ', x)
        print('y > ', y)

    def rd(self):
        getattr(obj_1, 'vw')(self)

if __name__ == '__main__':
    ob = obj_2()
    ob.r_data()

hope i could help, please let me know in the comments if you didn't understand anything. and if my comment helped you i would relly appreciate marking this comment as the answer :)

  • Related