Gabby Freeland
Gabby Freeland

Reputation: 1705

How do you set a default value for a variable in Python3?

For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces.

I don't know how to do this using the __init__ method because Python3 doesn't allow you to have more then one constructor method.

Right now it just looks like:

def __init__(self, name):
    self.type = "f:"
    self.name = name
    self.length = "0000"
    self.colon = ":"
    self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"]`    

Upvotes: 1

Views: 6504

Answers (4)

Xavier C.
Xavier C.

Reputation: 1981

You can use:

def __init__(self, name='your_default_name'):

Then you can either create an object of that class with my_object() and it will use the default value, or use my_object('its_name') and it will use the input value.

Upvotes: 3

ChE
ChE

Reputation: 88

Specify it as a default variable as shown below

def __init__(self, name=' '*9):
    self.type = "f:"
    self.name = name
    self.length = "0000"
    self.colon = ":"
    self.blocks = ["000", "000", "000", "000", "000", "000", "000","000","000","000", "000", "000"]

Upvotes: 1

Raskayu
Raskayu

Reputation: 743

Just set it like this, so for default will use 9 spaces

def __init__(self, name='        '):
        self.type = "f:"
        self.name = name
        self.length = "0000"
        self.colon = ":"
        self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000"]

More information

Upvotes: 1

viraptor
viraptor

Reputation: 34145

You can use default arguments:

def __init__(self, name='         '):

Upvotes: 0

Related Questions