我想设计一个名为houses
的类,其中包含街道地址,要价,卧室数量和房屋中的浴室数量。我还希望包括用于获取和设置每个数据字段的值的方法。
第一次使用课程。 我完成了课程设置,可以打印课程,但是不确定如何使用或使用哪种方法。
class houses:
def __init__(self, Adress, Askingprice, NumOfBedrooms, NumofBathroom):
self.Adress = Adress
self.Askingprice = Askingprice
self.NumOfBedrooms = NumOfBedrooms
self.NumofBathroom = NumofBathroom
def HouseDetails(self):
return "The house is at {} with a price of {} and has {} Bedroom/s and {} bathroom/s" \
.format(self.Adress, self.Askingprice, self.NumOfBedrooms, self.NumofBathroom)
house1 = houses("Almonaster_Avenue87", "R 500k", 1, 1)
house2 = houses("Audubon_Place33", "R 900k", 3, 3)
house3 = houses("Baronne_Street78", "R800k", 3, 2)
house4 = houses("Basin_Street55", "R700k", 2, 1)
house5 = houses("Bayou_Road11", "R 900", 4, 2)
house6 = houses("Bienville_Street78", "R700k", 2, 2)
house7 = houses("Bourbon_Street45", "R 800k", 4, 1)
house8 = houses("Broad_Street56", "R 900k", 5, 3)
print("\n",house1.HouseDetails())
请注意
要价中的“ R”是我的货币。
答案 0 :(得分:0)
如果必须具有getter和setter方法,这是使用Python内置的property
类的简洁方法。所示的create_property()
实用程序功能是Beazley&Jones(2013)的第三版 Python Cookbook 中食谱9.21的简化版本。
def create_property(name):
""" Utility to define repetitive property methods. """
storage_name = '_' + name
@property
def prop(self): # getter
return getattr(self, storage_name)
@prop.setter
def prop(self, value): # setter
return setattr(self, storage_name, value)
return prop
class House:
address = create_property('address')
asking_price = create_property('asking_price')
num_bedrooms = create_property('num_bedrooms')
num_bathrooms = create_property('num_bathrooms')
def __init__(self, address, asking_price, num_bedrooms, num_bathrooms):
self.address = address
self.asking_price = asking_price
self.num_bedrooms = num_bedrooms
self.num_bathrooms = num_bathrooms
def __str__(self):
return("The house is at {} with a price of {} and has "
"{} Bedroom/s and {} bathroom/s".format(self.address,
self.asking_price, self.num_bedrooms,
self.num_bathrooms))
house1 = House("Almonaster Avenue 87", "R 500k", 1, 1)
house2 = House("Audubon Place 33", "R 900k", 3, 3)
house3 = House("Baronne Street 78", "R 800k", 3, 2)
house4 = House("Basin Street 55", "R 700k", 2, 1)
house5 = House("Bayou Road1 1", "R 900", 4, 2)
house6 = House("Bienville Street 78", "R 700k", 2, 2)
house7 = House("Bourbon Street 45", "R 800k", 4, 1)
house8 = House("Broad Street 56", "R 900k", 5, 3)
print(house1)
输出:
The house is at Almonaster Avenue 87 with a price of R 500k and has 1 Bedroom/s and 1 bathroom/s