python 类的成员变量_在Python中访问类的成员变量?

答案,用几句话来说

在您的示例中,itsProblem是一个局部变量。

必须使用self来设置和获取实例变量。您可以在__init__方法中设置它。那么你的代码是:class Example(object):

def __init__(self):

self.itsProblem = "problem"

theExample = Example()

print(theExample.itsProblem)

但是如果您想要一个真正的类变量,那么直接使用类名:class Example(object):

itsProblem = "problem"

theExample = Example()

print(theExample.itsProblem)

print (Example.itsProblem)

但是要小心这个,因为theExample.itsProblem被自动设置为等于Example.itsProblem,但根本不是同一个变量,可以独立更改。

一些解释

在Python中,可以动态创建变量。因此,您可以执行以下操作:class Example(object):

pass

Example.itsProblem = "problem"

e = Example()

e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem

印刷品True

因此,这正是您对前面示例所做的。

实际上,在Python中,我们使用self作为this,但它不止于此。self是任何对象方法的第一个参数,因为第一个参数始终是对象引用。这是自动的,无论您是否称之为self。

也就是说你可以:class Example(object):

def __init__(self):

self.itsProblem = "problem"

theExample = Example()

print(theExample.itsProblem)

或:class Example(object):

def __init__(my_super_self):

my_super_self.itsProblem = "problem"

theExample = Example()

print(theExample.itsProblem)

完全一样。任何对象方法的第一个参数都是当前对象,我们只将其称为self作为约定。然后只向这个对象添加一个变量,就像从外部添加一样。

现在,关于类变量。

当你这样做时:class Example(object):

itsProblem = "problem"

theExample = Example()

print(theExample.itsProblem)

您会注意到,我们首先设置一个类变量,然后访问一个对象(实例)变量。我们从未设置过这个对象变量,但它是有效的,这怎么可能呢?

好吧,Python试图首先获取对象变量,但是如果找不到它,就会给您一个类变量。警告:类变量在实例之间共享,而对象变量不共享。

总之,不要使用类变量将默认值设置为对象变量。为此使用__init__。

最后,您将了解到Python类是实例,因此是对象本身,这为理解上述内容提供了新的见解。当你意识到这一点后,回来再看一遍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值