python类的成员没有访问控制限制,Python-访问类的受保护成员_

Given a class with some protected members and a public interface to modify them, when is it generally accepted to access the protected members directly? I have some specific examples in mind:

Unit testing

Internal private methods such as __add__ or __cmp__ accessing other's protected attributes

Recursive data structures (e.g. accessing next._data in a linked list)

I don't want to make these attributes public as I don't want them touched publicly. My syntax IDE syntax highlighting keeps saying that I'm wrong with accessing protected members - who is right here?

EDIT - adding a simple example below:

class Complex:

def __init__(self, imaginary, base):

self._imaginary = imaginary

self._base = base

def __str__(self):

return "%fi + %f" % self._base, self._imaginary

def __add__(self, other):

return Complex(self._imaginary + other._imaginary, self._base + other._base)

Pycharm highlights other._imaginary and other._base with the following:

Access to a protected member _imaginary of a class

解决方案

Solved - the problem was actually to do with lack of type-hinting. The below now works:

class Complex:

def __init__(self, imaginary, base):

self._imaginary = imaginary

self._base = base

def __str__(self):

return "%fi + %f" % self._base, self._imaginary

def __add__(self, other):

"""

:type other: Complex

:rtype Complex:

"""

return Complex(self._imaginary + other._imaginary, self._base + other._base)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值