Home > Mobile >  Setting self as an instance from another class doesn't work [Python]
Setting self as an instance from another class doesn't work [Python]

Time:01-20

Let's assume I have a class A and a class B.

class A:
    def __init__(self):
        self.variable1 = 1
        self.variable2 = 'sometext'

class B:

    def __init__(self, inst):
        self = inst
        print(self.__dict__.keys(), inst.__dict__.keys())

The print function returns

b = B(inst)
dict_keys(['variable1', 'variable2']) dict_keys(['variable1', 'variable2'])

However when I try

b.variable1

It returns the following error

AttributeError: 'B' object has no attribute 'variable1'

In my more complex code I need almost all variable from class A in class B. I tried using class inheritance however I couldn't make it work with class methods and constructors. Is there a reason why the above method doesn't work?

Thx

CodePudding user response:

You're trying to overwrite self, but that only works while you're in the init. Instead, try assigning the inst to a variable of the class B:

class B:
    def __init__(self, inst):
        self.inst = inst
        print(self.__dict__.keys(), inst.__dict__.keys())

Now you can access the variables of class A via:

inst = A()
b = B(inst)
b.inst.variable1

Not sure what you're trying to achieve here exactly, but you could also initiate the class A object inside the init of class B instead of passing the object to class B.

CodePudding user response:

To use variable from class A in B you have to access to class A from B. Then execute class B

class A:
    variable1 = 1
    variable2 = 'sometext'

class B:
    def __init__(self, inst=None):
        self.f1 = A().variable1
        self.f2 = A().variable2
    def get_var(self):
        print (self.f1)

B().get_var()
  • Related