在python中从类调用函数-不同的方式 [英] calling a function from class in python - different way

查看:259
本文介绍了在python中从类调用函数-不同的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢大家的帮助! 在添加@staticmethod上,它可以工作.但是我仍然想知道为什么我在这里遇到类型错误.

Thank you all for your help! on adding @staticmethod, it works. However I am still wondering why i am getting a type error here.

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

I have just started OOPS and am completely new to it. I have a very basic question regarding the different ways I can call a function from a class. I have a testClass.py file with the code:

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的文件中使用以下代码调用此类:

I am calling this class from another file called main.py with the following code:

from testClass import MathsOperations

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

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

This works without any issues. However, I wanted to use the class in a much simpler way.

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

I have now put the following code in the testClass.py file. I have dropped the init function this time.

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发生了什么错误吗?我如何使用此类?

this doesn't works. Can someone explain what is happening wrongly in case 2? How do I use this class?

我得到的错误是"TypeError:testAddition()恰好接受2个参数(给定3个)"

The error i get is "TypeError: testAddition() takes exactly 2 arguments (3 given)"

推荐答案

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

you have to use self as the first parameters of a method

在第二种情况下,您应该使用

in the second case you should use

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

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

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

and in your code you could do the following

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

如果您使用该类而不先实例化变量

if you use the class without instantiating a variable first

print MathOperation.testAddtion(2,3)

它给您一个错误"TypeError:未绑定方法"

it gives you an error "TypeError: unbound method"

如果要执行此操作,则需要 @staticmethod 装饰器

if you want to do that you will need the @staticmethod decorator

例如:

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

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

然后在您的代码中就可以使用

then in your code you could use

print MathsOperations.testAddition(2,3)

这篇关于在python中从类调用函数-不同的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆