Solving the problems in working with Python OOPs

Question:

I a trying to understand the Python OOP. I have came across the following errors; can someone suggest me the sources of the following errors and how to rectify them?

Code:

class Class1(object):
    def method_1(self, root):

        if root == None:
            return 0
        
        # Why do I require to write self.method_1 here?
        # NameError: global name 'method_1' is not defined
        d = abs(method_1(root.left))
        
        return d
    
    # NameError: name 'Class1' is not defined
    a = Class1()
    b = a.method_1(None)
    
    # TypeError: method_1() takes exactly 2 arguments (1 given)
    c = method_1(None)
    print(c)

class Class2(object):
   def method_2(self, root):
     # Is this correct way to call a method from Class2 
     j = Class1.method_1(None)

# This method can be called without self argument?

def method_3(self, root):
   d = abs(method_3(root.left))

   # How to call method of Class1 here in this method?
   e = method_1(None)
Asked By: Formal_this

||

Answers:

Why do I require to write self.method_1 here?

Method names must always be called on a class or instance. Even inside the class, they’re not available as ordinary functions.

NameError: name ‘Class1’ is not defined

Those lines of code need to be unindented so they’re not inside the class definition. The class name isn’t defined until after the class block is finished, so you can’t refer to it in code that runs while defining the class.

TypeError: maxDepth() takes exactly 2 arguments (1 given)

As explained above, you need to call the method on an instance. It should be

c = a.method_1(None)

Is this correct way to call a method from Class2

No. You need to make an instance, and call the method on the instance.

c = Class_1()
j = c.method_1(None)
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.