2015-11-02 67 views
1

我有這三類如何訪問Python中另一個類中定義的對象的屬性?

import datetime 

class MetalType(object): 
    Silver, Gold, Platinum = range(0, 3) 

class Metals(object): 
    def __init__(self,pType,pVariant): 
     self.type= pType 
     self.variant=pVariant 

class Transaction(object): 
    id=0 
    def __init__(self,pMetal,pQuantity,pTransType,pPrice): 
     Transaction.id+=1 
     self.transdate= datetime.date.today() 
     self.metal= pMetal 
     self.quantity =pQuantity 
     self.TransType =pTransType 
     self.price =pPrice 

現在我想創建一個交易對象,並打印類型

Silver=Metals(MetalType.Silver,"Heraus") 
Transaction1=Transaction(Metals,100,"buy",100.00) 
print(Transaction1.metal.type) 

但我得到以下錯誤

AttributeError: type object 'Metals' has no attribute 'type' 

我在做什麼這裏錯了嗎?

+2

'pMetal'是*類*,而不是*實例*。你的意思是'交易(銀,100,「買」,100.00)'? – jonrsharpe

+0

是的!我是一個白癡。謝謝你 – Rengas

+0

你也應該閱讀https://www.python.org/dev/peps/pep-0008/,我不認爲'id'正在做你想做的事情。 – jonrsharpe

回答

0
Transaction1=Transaction(Metals,100,"buy",100.00) 

應該成爲

Transaction1=Transaction(Silver,100,"buy",100.00) 

此外,友好的建議:爲不與類名混淆他們不使用大寫變量名。大寫字母的選擇使其難以發現。