Define a class with optional argument in Python

末鹿安然 提交于 2019-12-12 08:25:37

问题


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

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 will be '123000'

Or I can type

>>>a = class1()
>>>a.setdata('123','654')

a.data will be '123654'

How to achieve this? Thanks very much!


回答1:


Try this please:

def setdata(self, value1, value2 = '000'):
   Your code here



回答2:


Try defining a default argument, like so.

class class1():
    def setdata(self,value1, value2='000'):
        ...



回答3:


class class1:    
    def setdata(self,value1, value2=456):
        self.data = value1+value2
    def display(self):
        print(self.data)

may be this solves your problem



来源:https://stackoverflow.com/questions/10681038/define-a-class-with-optional-argument-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!