2015-04-01 126 views
0

我試圖實例化一個類實例化類:錯誤在Python

class Customer(object): 
    def __init__(self, name, money, ownership): 
     self.name = name 
     self.money = money 
     self.ownership = ownership 

    def can_afford(self): 
     x = False 
     for bike in bikes.values(): 

      if self.money >= bike.money * margin: 
       print "Customer {} can afford {}".format(self.name, bike) 
       x = True 
     if not x: 
      print "Customer {} cannot afford any bikes at this time.".format(self.name) 

shoppers = {   
    # Initial condition of shopper1 
    "Jane": Customer("Jane", 200, False), 
    # Initial condition of shopper2 
    "Alfred": Customer("Alfred", 500, False), 
    # Initial condition of shopper3 
    "Taylor": Customer("Taylor", 1000, False) 
} 

buyer = Customer(name, money, ownership) 

buyer = Customer(name, money, ownership)不斷得到出錯:

Undefined variable 'name' 
Undefined variable 'money' 
Undefined variable 'ownership' 

但我認爲我設置變量的值,在我的字典, 「客戶(......)」

+1

是的,你已經爲簡,阿爾弗雷德和泰勒奠定了基礎。什麼是單獨的「買方」實例化以及它的值應該來自哪裏? – 2015-04-01 15:57:12

回答

0
class Customer(object): 
    def __init__(self, name, money, ownership): 
     self.name = name 
     self.money = money 
     self.ownership = ownership 

    def can_afford(self): 
     x = False 
     for bike in bikes.values(): 

      if self.money >= bike.money * margin: 
       print "Customer {} can afford {}".format(self.name, bike) 
       x = True 
     if not x: 
      print "Customer {} cannot afford any bikes at this time.".format(self.name) 

shoppers = {   
    # Initial condition of shopper1 
    "Jane": Customer("Jane", 200, False), 
    # Initial condition of shopper2 
    "Alfred": Customer("Alfred", 500, False), 
    # Initial condition of shopper3 
    "Taylor": Customer("Taylor", 1000, False) 
} 
#this is solution for your MENTIONED problem only 
name = 'Buddy' 
money = 2 
ownership = 'something' 
buyer = Customer(name, money, ownership) 

解決方案爲您提到的問題是上面的,你只需要定義小號ome值。 但還有其他一些問題,比如bikes.values(),從哪裏來的?

請記住,要使用某些東西,你必須先告訴它是什麼,所以定義一些東西。

希望它有幫助。