繁体   English   中英

如何访问Python另一个类中定义的对象的属性?

[英]How to access an attribute of an object defined inside another class in 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

现在我想创建一个Transaction对象并打印类型

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

但我收到以下错误

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

我在这里做错了什么?

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

应该成为

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

另外,一个友好的建议:不要使用大写的变量名,以免将它们与类名混淆。 您对大写字母的选择使它比原来更难以发现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM