python静态变量的作用,在Python中访问父类的静态类变量

本文探讨了Python中如何从子类访问基类的私有变量,特别是带有双下划线前缀的变量。通过实例说明了这些变量是如何被名称改写以防止意外访问,并提供了推荐的做法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have someting like this

class A:

__a = 0

def __init__(self):

A.__a = A.__a + 1

def a(self):

return A.__a

class B(A):

def __init__(self):

# how can I access / modify A.__a here?

A.__a = A.__a + 1 # does not work

def a(self):

return A.__a

Can I access the __a class variable in B? It's possible writing a instead of __a, is this the only way? (I guess the answer might be rather short: yes :)

解决方案

So, __a isn't a static variable, it's a class variable. And because of the double leading underscore, it's a name mangled variable. That is, to make it pseudo-private, it's been automagically renamed to ___ instead of __. It can still be accessed by instances of that class only as __, subclasses don't get this special treatment.

I would recommend that you not use the double leading underscore, just a single underscore to (a) mark that it is private, and (b) to avoid the name mangling.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值