Instance methods of python

temp = n % 10
sum += temp * temp
temp //= 10

However, the problem with this code is that after computing the sum of squares, it tempperforms an incorrect division operation on which converts from an integer to a float and divides its value by 10. The correct operation should be integer division, ie , to ensure an integer quotient.temp /= 10temptemp //= 10

def getNumber(self,n:int) -> int:解释里面各参数和符号代表的意义
  • self: Indicates the class instance itself. In the method of the class, the first parameter is usually named self, which is used to refer to the current instance object.
  • n: Represents the input integer, which is a parameter of the method.
  • int: Indicates the parameter type annotation, specifying that the type of parameter n is an integer.
  • -> int: Indicates the return type annotation of the method, specifying that the type of the return value is an integer.

static method. Static methods are part of the class but do not require access to instance variables or other instance methods. @staticmethodYou can use a decorator on a class to declare a method as static.

Here is @staticmethodan example static method defined using a decorator:

class Solution:
    @staticmethod
    def getNumber(n: int) -> int:
        sum = 0
        while(n != 0):
            temp = n % 10
            sum += temp * temp
            temp //= 10
        return sum

In this example, getNumberthe method is a static method, which does not need to use selfkeywords to refer to the instance object. You can call the method directly by the class name, eg Solution.getNumber(123).

Guess you like

Origin blog.csdn.net/weixin_68798281/article/details/131969301