Instantiate class by passing only a few parameters in Python 3

Asked

Viewed 82 times

1

Good afternoon, everyone

I created a very simple python class with a constructor __init__. The constructor expects to receive 3 parameters, and the 3 have default value. I would like to know how to instantiate the class passing only parameter 1 and 3.

If I charge this way it works :

p = Person('Wagner')

That’s how it works too

p = Person('Wagner','xxx')

But in this way error occurs:

p = Person('Wagner', ,27)

Error:

File "Person.py", line 11
p = Person('Wagner', ,27)
                     ^
SyntaxError: invalid syntax

If I instantiate this way it also works

p = Person('Wagner','' ,27)

but supposing I had 10 parameters with values default and want to pass just the number 7,9,10 as I would ? I would be obliged to pass '' empty, even if they have a default value in the constructor ?

class Person:
    def __init__(self, name='not defined', last_name='not defined', age=0):
        self.name = name
        self.last_name = last_name
        self.age = age

    def printPerson(self):
        print("Name: " + self.name + "\nLast Name: " + 
              self.last_name + "\nAge: " + str(self.age))

2 answers

2


You can declare the name of the argument you are passing in Python.

class Person:
    def __init__(self, name = 'not defined', last_name = 'not defined', age = 0):
        self.name = name
        self.last_name = last_name
        self.age = age

p = Person(name = 'Wagner', age = 27)

2

If you have many arguments that need to be passed to a class, or even a function, it is recommended that you take another approach than positional arguments. Maybe keep nome as a positional (and mandatory) argument and leaving the rest as keyword arguments (and optional):

class Person:
    def __init__(self, name, **kwargs):
        self.name = name
        self.last_name = kwargs.get("last_name", "n/a")
        self.age = kwargs.get("age", 0)

    def __str__(self):
        return f"{self.name} {self.last_name} | {self.age}"

And a basic test:

a = Person("Wagner")
b = Person("Wagner", last_name="Rodrigues")
c = Person("Wagner", age=27)
d = Person("Wagner", last_name="Rodrigues", age=27)

for i in [a, b, c, d]:
    print(i)

Returning:

Wagner n/a | 0
Wagner Rodrigues | 0
Wagner n/a | 27
Wagner Rodrigues | 27

This way new arguments that need to be passed into the class through keywords and in the constructor you define what the default value is if it is omitted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.