【问题标题】:When calling a class method in another file do we have to provide the value for self?在另一个文件中调用类方法时,我们是否必须为 self 提供值?
【发布时间】:2021-03-24 08:25:33
【问题描述】:

我正在尝试将另一个文件中的方法调用到另一个文件中,并且它已被导入,但是在调用它时说未定义 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(no-value-for-parameter) 中的参数“self”没有值

【问题讨论】:

  • 请复制粘贴代码,不要发布图片。
  • @Amen 请编辑您的帖子以包含代码。不要在 cmets 中发送它,因为它不可读。
  • 这与文件无关。在定义ArithmeticMethod 的文件中运行ArithmeticMethod.addition(value1=10, value2=9) 时,您会得到完全相同的行为。你能解释一下为什么你在一个类中定义操作,这意味着一个实例self,而操作实际上并不需要这个实例?
  • 一开始就没有真正的理由将其定义为一个类。你只需要 4 个常规函数(顺便说一下,它们都在 operator 模块中定义。)

标签: python methods parameters


【解决方案1】:

当你这样做时:

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))

【讨论】:

  • 谢谢,但随后出现此错误:方法应将“self”作为第一个参数pylint(no-self-argument)
  • @Amen 我已经编辑了帖子以消除警告。
  • 啊,我看到了一个装饰器。非常感谢。
  • FWIW,更好的方法似乎一开始就没有课程。 arithmetic 模块应直接包含 addition 函数(等)。
【解决方案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)

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    相关资源
    最近更新 更多