【发布时间】:2021-05-29 03:42:53
【问题描述】:
所以这个简单的程序应该只检查房产的现有所有者、当前所有者、销售价格和其他一些信息。我昨晚刚学了一点 oop,我想知道是否有办法忽略或跳过某些位置参数,让它们默认为类中的变量。
所以在下面我的“house2”实例中,这表示一栋刚刚建造的房子,因此它没有任何当前所有者或以前的所有者。
不要为我没有的值输入 None,(以前的所有者,当前的所有者)在那里我可以说,“嘿,跳过位置参数‘当前所有者’和‘以前的所有者’,只使用变量而是在课堂内”。这样一来,我就不用为每个不存在的值输入 None 了。
所以我的实例应该是这样的:
house2 = houseStats('77 Book Worm St', 'Inner-City', 1, 1, '120000')
与此相比:
house2 = houseStats('77 Book Worm St', 'Inner-City', 1, None, None, 1, '120000')
下面的完整代码块:
# A simple program to get information of a house.
class houseStats:
# class variables to default to if there are no instance variables.
current_owner = 0
previous_owner = 0
forsale = 0
def __init__(self, address, area, houseAge, currentOwner, previousOwner, forSale, salePrice):
self.address = address
self.area = area
self.house_age = houseAge
self.current_owner = currentOwner
self.previous_owner = previousOwner
self.forsale = forSale
self.saleprice = salePrice
# Function to determine the house age
def houseage(self):
return f"This house is {self.house_age} years old"
# Function to determine whether the house is for sale and who sold it.
def sold(self):
if self.forsale is None:
print("House is currently not for sale..")
else:
print(f'House is currently for sale for ${int(self.saleprice)}')
house1 = houseStats('19 Galaxy Way', 'Suburbs', 5, 'Douglas Forword', None, 1, 10000)
house2 = houseStats('77 Book Worm St', 'Inner-City', 1, None, None, 1, '120000')
house1.sold()
【问题讨论】:
-
默认值必须在最后。考虑为这样的函数使用命名参数——在这里很难说出每个字段对应的内容。
-
当需要这些参数时,应该使用位置参数。如果它们不是必需的,它们应该是具有默认值的关键字参数,然后您可以在函数中随意处理。
-
要跳过一个参数,你必须默认它,例如
param=None。为了默认一个参数,它后面不需要有任何 unDefaulted 参数。所以把它们移到最后。 -
我可以举个例子作为答案吗?我对它应该是什么样子有点困惑。
标签: python python-3.x class arguments instance