pythonpython-3.xoopattributespython-3.8

How can you access an object from a different class into one class in Python?


How can I access an object from a different class into another class?

class Hello:
     def say_hello (self):
          print("Hello!")

class Robot:
     def hello (self):
          a = Hello()
          a.say_hello()

For example, in the following code, I have a "Hello" and "Robot" class. I want the Robot to say "hello" by taking the "say_hello" method from the "Hello" class. In this particular code, it works. However, for more complicated code, will the same thing work?

Thank you very much in advance.


Solution

  • class Hello:
     def say_hello (self):
          print("Hello!")
    
    class Robot:
     def hello (self):
          a = Hello()
          a.say_hello()
     y = Robot()
     y.hello()
    

    Works as attended.