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

本文探讨了面向对象编程中类和方法的使用。首先,通过一个简单的例子展示了如何在Python中定义和实例化类。然后,解释了在不使用`__init__`方法时,直接定义函数作为类的方法会导致的问题,即需要指定`self`参数。最后,提到了`@staticmethod`装饰器的作用,它允许将方法与类而不是特定的实例关联,从而可以不通过实例调用类方法。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

EDIT2: Thank you all for your help!

EDIT: on adding @staticmethod, it works. However I am still wondering why i am getting a type error here.

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)

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.

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

calling this using;

from testClass import MathsOperations

xyz = MathsOperations()

print xyz.testAddition(2, 3)

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

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

解决方案

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)

it gives you an error "TypeError: unbound method"

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

For example:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值