在另一个文件中调用类方法时,我们是否必须为self提供值?

2024-10-01 22:29:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个方法从另一个文件调用到另一个文件中,该方法已导入,但调用时表示未定义self参数。我是一个初学者程序员,需要帮助:(

类别:

class ArithmeticMethod:
    def __init__(self):
        print('Arithmetic Class Init.')

    def addition(self, value1, value2):
        answer = int(value1) + int(value2)
        return answer


    def subtract(self, value1, value2):
        answer = int(value1) - int(value2)
        return answer


    def multiply(self, value1, value2):
        answer = int(value1) * int(value2)
        return answer


    def divide(self, value1, value2):
        answer = int(value1) / int(value2)
        return answer

电话:

from arithmetic import ArithmeticMethod

print(ArithmeticMethod.addition(value1=10, value2=9))

错误: 未绑定方法callpylint中的参数“self”没有值(参数没有值)


Tags: 文件方法answerself参数returndefint
2条回答

当您这样做时:

def addition(self, value1, value2):
    result = int(value1) + int(value2)
    return result

您是说addition方法与实例绑定(因为self是第一个参数)。因此,当您调用它时,您必须构造一个实例来调用它:

myArith = ArithmeticMethod()
print(myArith.addition(1, 2))

显然,这很愚蠢,因为您不需要任何实例,而且self参数未使用。所以,去掉它并用@staticmethod注释它:

@staticmethod
def addition(value1, value2):
    result = int(value1) + int(value2)
    return result

现在,您可以将其作为静态方法调用,而无需通过实例:

print(ArithmeticMethod.addition(1, 2))

将文件命名为arithmetic.py

只需定义方法,所有方法对类都是静态的,与类无关

def addition(value1, value2):
    return int(value1) + int(value2)

def subtract(value1, value2):
    return int(value1) - int(value2)

def multiply(value1, value2):
    return int(value1) * int(value2)

def divide(value1, value2):
    return int(value1) / int(value2)

将其用于:

import arithmetic

a = arithmetic.addition(3,6)

from arithmetic import addition

a = addition(3,6)

相关问题 更多 >

    热门问题