Define a class with optional argument in Python

24,112

Solution 1

Try this please:

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

Solution 2

Try defining a default argument, like so.

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

Solution 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

Share:
24,112
Admin
Author by

Admin

Updated on July 11, 2020

Comments

  • Admin
    Admin almost 4 years
    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!

  • Li-aung Yip
    Li-aung Yip almost 12 years
    You should try to link to a newer version of the Python documentation. Python 1.x is a historical fossil these days.
  • XORcist
    XORcist almost 12 years
    For an explanation including the point where most people trip over: network-theory.co.uk/docs/pytut/DefaultArgumentValues.html
  • cheeken
    cheeken almost 12 years
    @Li-aungYip Excellent point, I will update the link. I was posting from my phone, so my requirements may have been lax. :)
  • Mausy5043
    Mausy5043 about 6 years
    pep8 recommends no spaces around equalsign.