简体   繁体   中英

call a method inside classmethod in python

I am learning python and stucked in a problem

Suppose I have a class:

class Xyz:
    def __init__(self):
        self.number=25
    
    def square(self):
        return self.number*self.number
    
    @classmethod
    def getsquare(cls):
        return cls.square()

#Now let's call getsquare() method
sq=Xyz.getsquare()

I am getting an error:

TypeError: square() missing 1 required positional argument: 'self'

My attempt:

I tried to make square() function as classmethod and then calling the getsquare() method but still I am getting an error (I guess it was because since we aren't creating an object of class so due to this number is not initialising)

but if I do like this it's working:

class Xyz:
    
    def square():
        number=25
        return number*number
    
    @classmethod
    def getsquare(cls):
        return cls.square()

so How to call a class function inside classmethod?

any help or clue will be appriciated

Some mistakes I see here, but I am going to answer the syntax question

@classmethod / @staticmethod decorate a method as a static member for the class. By definition, they do not reference to any object and have several restrictions:

  • They can only directly call other static method
  • They can only directly access static data
  • They cannot refer to self or super in any way

In your code, getsquare is a static method and square is a instance method. So, getsquare violates the first rule because of it is calling to square

cls is just an uninstantiated class object, calling return cls.square() is analogous to calling Xyz.square() , which obviously doesn't work because its not a @classmethod . Try first initiating the class inside getsquare before calling any methods:

class Xyz:
    def __init__(self):
        self.number=25
    
    def square(self):
        return self.number*self.number
    
    @classmethod
    def getsquare(cls):
        return cls().square()

#Now let's call getsquare() method
sq=Xyz.getsquare()

Why the second example works, the simple answer is because it doesn't have an __init__ defined so it's doesn't know how to initialize so it's not needed.

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