2

I'm in the process of learning Python through a book, one of the questions was to create a class called Country which held the parameters shown below, then to create a method called is_larger that would return a boolean indicating whether the first country was larger, in area, than the other considering this code:

>>> canada = Country( 'Canada', 34482779, 9984670)
>>> usa = Country( 'United States of America' , 313914040, 9826675)
>>> canada. is_larger(usa)
True

Here's the solution from the book:

class Country():

    def __init__(self, name, population, area):
        """ (Country, str, int, int)

        A new Country named name with population people and area area.

        >>> canada = Country('Canada', 34482779, 9984670)
        >>> canada.name
        'Canada'
        >>> canada.population
        34482779
        >>> canada.area
        9984670
        """ 

        self.name = name
        self.population = population
        self.area = area

    def is_larger(self, other):
        """ (Country, Country) -> bool

        Return whether this country is larger than other.

        >>> canada = Country('Canada', 34482779, 9984670)
        >>> usa = Country('United States of America', 313914040, 9826675)
        >>> canada.is_larger(usa)
        True
        >>> usa.is_larger(canada)
        False
        """ 

        return self.area > other.area

I can apply this after seeing the answer, but I just don't understand the process and I'm keen on fully understanding the code. Method is_larger holds two parameters, one being self. Should the method not be:

def is_larger(self, country1, country2):

How was an object used as the self parameter?

If my question is confusing, please let me know and I'll try to clarify what's going on in my head lol.

martineau
  • 119,623
  • 25
  • 170
  • 301
Yabusa
  • 579
  • 1
  • 6
  • 15

1 Answers1

2

The call

canada.is_larger(usa)

can be thought of as syntactic sugar for

Country.is_larger(canada, usa)

The parameter self (really, the first argument to the method, regardless of what you name it) refers to the object that invokes the method. Here, whether you use the first form or the second form, self == canada and other == usa.

chepner
  • 497,756
  • 71
  • 530
  • 681