Anas Yusef
Anas Yusef

Reputation: 319

How to use a variable that inside of a function of a class in another class - Python

I am trying to access to another variable that inside a function and also that is from another class, so I coded it in that way

class Helloworld:

   def printHello(self):
       self.hello = 'Hello World'
       print (self.hello)


class Helloworld2(Helloworld):
    def printHello2(self)
       print(self.hello)

b = Helloworld2()
b.printHello2()

a = Helloworld()
a.printHello()

However, this gives me that error: AttributeError: 'Helloworld2' object has no attribute 'hello'. So, what would be the simplest way to access to that variable?

Upvotes: 0

Views: 52

Answers (2)

Baldrickk
Baldrickk

Reputation: 4409

You should initialise the instance of the class via the __init__() function, this means that when it is created, these values are set.

That would make your code look like:

class Helloworld:
    def __init__(self):
        #sets self.hello on creation of object
        self.hello = 'Hello World'

    def printHello(self):
        print (self.hello)


class Helloworld2(Helloworld):
    def printHello2(self):
       print(self.hello)

b = Helloworld2()
b.printHello2()

a = Helloworld()
a.printHello()

An alternative, with your current code is to just call printHello(), either at the top level, with b.printHello(), or within printHello2. Note that in this case, you don't actually need to use super().printHello() as you are not re-defining that function in Helloworld2, though it would be required if you did.

Upvotes: 1

vishes_shell
vishes_shell

Reputation: 23484

That's because you never call printHello(self) that declare your self.hello.

To make it work you need to do:

class Helloworld2(Helloworld):
    def printHello2(self):
        super().printHello()
        print(self.hello)

Or move declaration of you self.hello to __init__() which would be more preferred way.

Upvotes: 2

Related Questions