繁体   English   中英

是否可以在python的类中单独访问实例属性?

[英]Is it possible to access instance attributes separately in a class in python?

在下面的代码中,如果我将帐户实例创建为accnt并写入accnt.owner,则程序将返回内存位置,而不是该位置的值。 如果我对所有者和余额使用str ()方法,则可以同时获取accnt.owner和accnt.balance值。是否可以通过仅键入accnt.owner)\\ n accnt.balance来分别访问它们打印功能?

class Account():

    def __init__(self,owner,balance):

        self.owner = owner
        self.balance = balance

accnt = ("Jose",100)
acct.owner----> Should output Jose
acct.balance---->Should output 100

您犯了一个错误,必须指出要实例化的类:

class Account():

    def __init__(self, owner, balance):

        self.owner = owner
        self.balance = balance

accnt = ("Jose", 100) # <------------- This is wrong
accnt = Account("Jose",100) # <------- This is right
print(acct.owner)
print(acct.balance)

当您从控制台调用变量时,它会被打印出来,但是从代码脚本中,您必须使用print()

在此处输入图片说明

暂无
暂无

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

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