在 Python 中定义一个带有可选参数的类 [英] Define a class with optional argument in Python
本文介绍了在 Python 中定义一个带有可选参数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class class1():
def setdata(self,value1, value2):
self.data = value1+value2
def display(self):
print(self.data)
对于上面的代码,当我使用它时.它将正好需要两个参数.
For the above code, when I use it. It will require exactly two arguments.
>>>a = class1()
>>>a.setdata('123','456')
但是如果我想为value2
设置一个default value
,例如,它的(value2
)默认值为'000'
.
But what if I want to set a default value
for value2
, for exmaple, its(value2
) default value is '000'
.
下次我使用这个类时,我可以输入
Next time when I use the class, I can either type
>>>a = class1()
>>>a.setdata('123')
a.data
将是 '123000'
或者我可以输入
>>>a = class1()
>>>a.setdata('123','654')
a.data
将是 '123654'
如何实现?非常感谢!
推荐答案
请试试这个:
def setdata(self, value1, value2 = '000'):
Your code here
这篇关于在 Python 中定义一个带有可选参数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文