这个问题是风格之一。由于这些属性在python中不是私有的,因此使用类似的方法在类外部直接解决这些属性是一种好习惯my_obj.attr吗?或者,也许最好还是通过成员函数来做到这一点,就像get_attr()在c ++中那样,这是通常的做法?
3 回答

蓝山帝景
TA贡献1843条经验 获得超7个赞
听起来像您想使用属性:
class Foo(object):
def __init__(self, m):
self._m = m
@property
def m(self):
print 'accessed attribute'
return self._m
@m.setter
def m(self, m):
print 'setting attribute'
self._m = m
>>> f = Foo(m=5)
>>> f.m = 6
setting attribute
>>> f.m
accessed attribute
6
这是访问变量的最自适应方法,对于简单的用例,您不需要这样做,并且在Python中,您始终可以更改设计以稍后使用属性,而无需付出任何代价。

MM们
TA贡献1886条经验 获得超2个赞
首先创建该类的实例:
myinstance = MyClass()
myinstance.attr
否则,您会收到类似AttributeError: class MyClass has no attribute 'attr'尝试执行时的错误消息MyClass.attr
添加回答
举报
0/150
提交
取消