Home > Enterprise >  Add variable value for a specific variable but in another class
Add variable value for a specific variable but in another class

Time:09-06

to keep everything simple, I use a normal sample code and nothing from my project.

class ClassA(object):
   def __init__(self):
       self.var1 = 1   # I want to give the value "1" in the other class!
       self.var2 = 2

   def methodA(self):
       self.var1 = self.var1   self.var2
       return self.var1



class ClassB(ClassA):
   def __init__(self, class_a):
       self.var1 = class_a.var1
       self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print(sum) 

How can I define/give the value of var1 of ClassA in ClassB? (see my comment: "# I want to give the value "1" in ClassB!") I need something like the set method we use in java oder something similr, I can use in python.

CodePudding user response:

ClassB inherits ClassA, so it will have var1 if you call ClassA __init__. You need to do it from ClassB __init__ instead of creating seperate object and sending it as value

class ClassB(ClassA):
    def __init__(self):
        super().__init__()

object2 = ClassB()
print(object2.var1) # 1
  • Related