gpt4 book ai didi

python - 对象用作 "self"参数?

转载 作者:行者123 更新时间:2023-12-01 02:00:21 31 4
gpt4 key购买 nike

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

>>> 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参数?

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

最佳答案

来电

canada.is_larger(usa)

可以被认为是语法糖

Country.is_larger(canada, usa)

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

关于python - 对象用作 "self"参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723251/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com