0

I am using a package which defines a couple of classes (A & B). I want to extend class A in my main.py to include var_d. I have tried the following:

File: my_package.py

class A:
    def __init__(self):
        self.var_a = 'var_a'

class B:
    def __init__(self):
        self.var_b = A()
        self.var_c = A()

File: main.py

from my_package import *

a = B()
a.var_b.var_d = 'extending class A to have this new var'

This doesn't work. What's an alternate solution?

2 Answers2

1

You have to use "setattr"

class A:
    def __init__(self):
        self.var_a = 'var_a'

class B:
    def __init__(self):
        self.var_b = A()
        self.var_c = A()
a = B()
setattr(a.var_b, 'var_d', 1)

leads to

print(a.var_b.var_d)
>> 1
b0lle
  • 732
  • 6
  • 19
  • This works but is it possible to do it such that class A is extended? So that `a.var_c.var_d` is also set? – Mustafa Hussain Jul 14 '20 at 10:03
  • Ah you ment something like "static variables". You can use static variables with the property keyword. But class A have to know about the property during initialization. This answer https://stackoverflow.com/a/27568860/8386455 is great to learn about static variables – b0lle Jul 14 '20 at 10:16
0

In your class A, the self.var_a is not assigned value. The variables in python exist automatically in the first scope where they're assigned. In your current code, self.var_a was not assigned. If you do self.var_a = '' for example, it should be working.

update:I may get confused about what you are asking. Your error code complains about 'var_a', that what my answer for.

SuShiS
  • 73
  • 1
  • 3
  • 13