我目前正在学习Thinkful Python课程,但无法弄清楚如何在另一个类中使用一个类的self属性。
class Bicycle(object):
# Have a model name
# Have a weight
# Have a cost to produce
def __init__(self, model):
self.model = model
pass
class BicycleShop(object):
# Create a bicycle shop that has 6 different bicycle models in stock. The shop should charge its customers 20% over the cost of the bikes
margin = 1.2
# Have a name
# Have an inventory of different bikes
# Sell bikes with a margin over their cost
# Can see a total of how much profit they have made
def __init__(self, company_name, models):
self.company_name = company_name
self.models = models
def bicycle_models(self):
for model in self.models.keys():
print(model)
def bicycle_prices(self):
for model, price in self.models.items():
if price <= customer_1.budget:
print("The {} is available for a price of ${:.2f}.".format(model, price * self.margin))
class Customer(object):
# Have a name
# Have a fund of money used to purchase the bike
# Can buy and own a new bicycle
def __init__(self, name, budget):
self.name = name
self.budget = budget
def check_funds(self):
return evans_cycles.bicycle_prices()
evans_cycles = BicycleShop("Evans Cycles", { "BMC Road Machine": 125, "Cannondale Synapse": 275, "Pinnacle Laterite": 450, "Fuji Transonic": 625, "Cervelo R2": 750, "Specialized Roubaix": 999 })
print("\nWe are {} Bicycle Shop. Please see our range of bikes, below.\n".format(evans_cycles.company_name))
evans_cycles.bicycle_models()
customer_1 = Customer('Stuart', 1000)
print("\nHello, I'm {} and my budget is ${}. What can I afford?\n".format(customer_1.name, customer_1.budget))
print(customer_1.check_funds())
目前,我已经将customer_1.budget中的硬编码编码为bike_prices方法,并将evans_cycles硬编码为check_funds函数。但是我知道这不是正确的方法,但是我不知道该怎么做。
在另一个类别中利用一个类别的属性的正确方法是什么?我试图使用继承,但是它没有用,它不会接受我的字典作为我认为的参数。
每当您设计某些东西时,都必须考虑关系。那么客户与商店有什么关系?好吧,假设每个商店都有客户,而每个客户只有一个商店(举个例子,不一定要是真的)。在这种情况下,您会
class BicycleShop:
...
class Customer:
def __init__(self, shop):
self.shop = shop
因此,现在客户可以参考商店。现在,您可以get_models()
在商店中公开功能:
class BicycleShop:
def get_models(self):
return self.models
最后check_funds
在Customer
:
class Customer:
def __init__(self, name, budget, shop):
self.name = name
self.shop = shop
self.budget = budget
def check_funds(self):
models = self.shop.get_models()
for model, price in models.items():
if price <= self.budget:
print("The {} is available for a price of ${:.2f}.".format(model, self.get_price(model)))
您还必须实施def get_price(self, model)
方法,BicycleShop
因为(再次关系)价格不仅取决于模型,而且取决于商店。然后它会像这样:
evans_cycles = BicycleShop("Evans Cycles", { "BMC Road Machine": 125, "Cannondale Synapse": 275, "Pinnacle Laterite": 450, "Fuji Transonic": 625, "Cervelo R2": 750, "Specialized Roubaix": 999 })
print("\nWe are {} Bicycle Shop. Please see our range of bikes, below.\n".format(evans_cycles.company_name))
customer_1 = Customer('Stuart', 1000, evans_cycles)
customer_1.check_funds()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句