python - Can't access variable from another class? -


here code

class a():    def __init__(self):        self.say_hello = "hello"     def donea(self):        print "a done"  class b(a):    def __init__(self):        print self.say_hello     def doneb(self):        print "b done"  = a() b = b()  a.donea() b.doneb() 

when run error attributeerror: b instance has no attribute 'say_hello'

you need add call super in constructor of class b, otherwise say_hello never created. this:

class b(a):    def __init__(self):        super(b, self).__init__()        print self.say_hello     def doneb(self):        print "b done" 

if you're doing in python 2 (which apparently based on print statements), you'll have make sure you're using "new style" class instead of old-style class. having a class inherit object, so:

class a(object):     def __init__(self):         self.say_hello = "hello"      def donea(self):         print "a done"  class b(a):     def __init__(self):         super(b, self).__init__()         print self.say_hello      def doneb(self):         print "b done"  = a() b = b()  a.donea() b.doneb() 

running script gives:

hello done b done 

Comments

Popular posts from this blog

Capture and play voice with Asterisk ARI -

c++ - Can not find the "fiostream.h" file -

visual studio - Installing Packages through Nuget - "Central Directory corrupt" -