Python Challenge of the Day (2/17/22)

Problem scenario
You have a program as follows:

class Location:
    def __init__(self, country="US", state="CA", city="Los Angeles"):
        self.country = country
        self.state = state
        self.city = city

    def printer(self):
        return [self.country, self.state, self.city]

new_loc = Location("Mexico", "Mexico City", "Mexico City", "good neighborhood")
print(new_loc.printer())

Here are your choices of what it could print out:

a. TypeError: init() takes from 1 to 4 positional arguments but 5 were given
b. TypeError: init() takes from 1 to 3 positional arguments but 4 were given
c. ['Mexico', 'Mexico City', 'Mexico City']
d. None of the above

Which one does it print?

Scroll down to see the answer.


Answer
A. The reason is that the class methods always pass the self when there are stanzas like this:

new_loc = Location("Mexico", "Mexico City", "Mexico City", "good neighborhood")

The self is invisible, but behind-the-scenes, it is there.

It accepts four positional arguments: country, state, city, and self. The line causing the error includes "good neighborhood". To read more about this, see this StackOverflow posting.

The arity of the __init__ constructor (in the class Location) is variable -- but passing four arguments is excessive. It can handle three explicit parameters as "self" is passed implicitly. Python will print out "__init__() takes from 1 to 4 positional arguments but 5 were given"

Leave a comment

Your email address will not be published. Required fields are marked *