0

I want to access variable inside a method of parent class my code looks like this

class func1:
    def show(self):
        self.data = 123
        self.next = 100 

    def new(self):
        self.num = self.data + self.next
        print(self.num)



class func2(func1):
    def new_num(self):
        self.new = self.num * 3 
        print(super.num)

but this gives attribute error

AttributeError: 'func2' object has no attribute 'num'

Satyam
  • 1
  • I believe this will help you get started. You need to use `def __init__(self)`: https://stackoverflow.com/questions/10064688/cant-access-parent-member-variable-in-python – Andrew Halpern May 24 '20 at 05:11
  • `self.num` is assigned by the `new` method. It won't exist until you call that method in your derived class object. – tdelaney May 24 '20 at 05:11

1 Answers1

1

Variables don't appear in an instance object until something assigns them values. In your case, code that wants to call new_num must first call show and new to set self.num.

class func1:
    def show(self):
        self.data = 123
        self.next = 100 

    def new(self):
        self.num = self.data + self.next
        print(self.num)



class func2(func1):
    def new_num(self):
        self.new = self.num * 3 
        #print(super.num) # todo: I think this was just debug code...?

foo = func2()
foo.show()
foo.new()
foo.new_num()
tdelaney
  • 73,364
  • 6
  • 83
  • 116