-1

I am trying to understand python inheritance a little. Here is a use case:

class Test:

    def hello():
        print("hello")
        return "hello"

    def hi():
        print(hello())
        print("HI")

class Test1(Test):
    hi()
    pass

x = Test1()
x.hello()

I don't understand why I can't call "hi()" in class Test1. It inherited it class Test right?

ozn
  • 1,990
  • 3
  • 26
  • 37

1 Answers1

0

I think you are misunderstanding the relationship and definitions of classes and objects. Classes are like blueprints to create objects. By writing methods inside a class, you are essentially defining the behaviors of the object that can be created from the class blueprint. So, with your code:

class Test:

    def hello():
        print("Hello")
        return "Hello"

    def hi():
        print(hello())
        print("Hi")


class Test1(Test):

    hi() # <- You really shouldn't call a method directly from a "blueprint" class
    pass

x = Test1()
x.hello()

While your last two lines of code are valid, it's a bad idea (and almost always invalid) to call a method outside of the class's scope directly inside a class definition. The reason why hi() does not work in the Test1 class is that it's not defined in the scope of Test1; even though this class indeed inherits from the Test class, it only affects the object that is created from the class (like the object x you created from the Test1() class).

Here's a more detailed explanation about classes and objects from another relevant question: What are classes, references and objects?

Hope this helped!

Jerrybibo
  • 1,315
  • 1
  • 21
  • 27