gpt4 book ai didi

python - 在 python 中从类调用函数 - 不同的方式

转载 作者:太空狗 更新时间:2023-10-29 19:31:41 25 4
gpt4 key购买 nike

EDIT2:谢谢大家的帮助!编辑:在添加@staticmethod 时,它起作用了。但是我仍然想知道为什么我在这里遇到类型错误。

我刚刚开始使用 OOPS,对它完全陌生。关于从类中调用函数的不同方式,我有一个非常基本的问题。我有一个带有代码的 testClass.py 文件:

class MathsOperations:
def __init__ (self, x, y):
self.a = x
self.b = y
def testAddition (self):
return (self.a + self.b)

def testMultiplication (self):
return (self.a * self.b)

我使用以下代码从另一个名为 main.py 的文件中调用此类:

from testClass import MathsOperations

xyz = MathsOperations(2, 3)
print xyz.testAddition()

这没有任何问题。但是,我想以更简单的方式使用该类。

我现在已将以下代码放入 testClass.py 文件中。这次我放弃了 init 函数。

class MathsOperations:
def testAddition (x, y):
return x + y

def testMultiplication (a, b):
return a * b

调用这个使用;

from testClass import MathsOperations
xyz = MathsOperations()
print xyz.testAddition(2, 3)

这行不通。有人可以解释案例 2 中发生了什么错误吗?我如何使用这个类?

我得到的错误是“TypeError: testAddition() takes exactly 2 arguments (3 given)”

最佳答案

你必须使用self作为方法的第一个参数

在第二种情况下你应该使用

class MathOperations:
def testAddition (self,x, y):
return x + y

def testMultiplication (self,a, b):
return a * b

在您的代码中,您可以执行以下操作

tmp = MathOperations()
print tmp.testAddition(2,3)

如果你在没有先实例化一个变量的情况下使用这个类

print MathOperation.testAddtion(2,3)

它给你一个错误“TypeError: unbound method”

如果你想这样做,你需要 @staticmethod装饰器

例如:

class MathsOperations:
@staticmethod
def testAddition (x, y):
return x + y

@staticmethod
def testMultiplication (a, b):
return a * b

然后在你的代码中你可以使用

print MathsOperations.testAddition(2,3)

关于python - 在 python 中从类调用函数 - 不同的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com