【问题标题】:Object used as "self" argument? [duplicate]用作“自我”论点的对象? [复制]
【发布时间】:2018-09-18 06:43:08
【问题描述】:

我正在通过一本书学习 Python,其中一个问题是创建一个名为 Country 的类,该类包含下面显示的参数,然后创建一个名为 is_larger 的方法,该方法将返回一个布尔值,指示是否第一个考虑到这个代码,国家在面积上比其他国家更大:

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

这是书中的解决方案:

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

我可以在看到答案后应用它,但我只是不明白这个过程,我渴望完全理解代码。 方法 is_larger 有两个参数,一个是 self。方法不应该是:

def is_larger(self, country1, country2):

如何将对象用作 self 参数?

如果我的问题令人困惑,请告诉我,我会尽力澄清我的想法,哈哈。

【问题讨论】:

    标签: python python-3.x oop methods


    【解决方案1】:

    电话

    canada.is_larger(usa)
    

    可以被认为是语法糖

    Country.is_larger(canada, usa)
    

    参数self(实际上,该方法的第一个参数,不管你如何命名它)指的是调用该方法的对象。在这里,无论您使用第一种形式还是第二种形式,self == canadaother == usa

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多