简体   繁体   中英

Can a class method call an instance method in python?

I am learning to program a binary tree and I want to check if a given number is already in the tree so when I try to add the same number it stops.

class Node:

    exist = True

    @classmethod
    def num_exist(cls, n):
        cls.exist = cls.find(n)


    def find(self, n):

        if n != self.value:
            if n < self.value:
                if self.right != None:
                    self.right.find(n)

                else:
                    return False

            if n > self.value:
                if self.left != None:
                    self.left.find(n)

                else:
                    return False
        else:
            return self


    def add(self, n):

        self.num_exist(n)

        if self.exist == False:
            if n != self.value:
                if n < self.value:
                    if self.right != None:
                    self.add(n)

                else:
                    self.right = Node(n)

            if n > self.value:
                if self.left != None:
                    self.add(n)

                else:
                    self.left = Node(n)

The problem here is that when I call the function num_exist() it gives me the following error:

TypeError: find() missing 1 required positional argument: 'n'

I suppose this error is because the self parameter hasn't been passed, but I don't know how to do it or if it is possible to pass the function find() to the @classmethod . I'm pretty newbie in oop.

What you are trying to do makes no sense. You are trying to find the number n in a given tree , which is an instance, so what does it mean for it to be a class method?

Can a class method call an instance method? Technically yes, as long as you pass in a reference to that instance:

class MyClass:
    def __init__(self, a):
        self.a = a

    def print_a(self):
        print(self.a)

    @classmethod
    def class_print_a(cls, inst):
        inst.print_a()

my_instance = MyClass(a=1)
MyClass.class_print_a(my_instance)  # output: 1

... Although you really should have a good reason for doing so. If your class method depends on a particular instance , then it's not really a class method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM