2 回答
TA贡献1943条经验 获得超7个赞
您已经成功地添加/修改了类实例。即,__init__获取一些a并将其作为属性添加.a到实例self。对变量和属性使用相同的名称是偶然的——您也可以使用不同的名称:
class Bla:
def __init__(self, b):
self.a = b # add `b` as attribute `a`
一旦将属性添加到实例,默认情况下可以自由读取和覆盖该属性。这适用于初始方法、其他方法以及可以访问实例的任何其他函数/方法。
class Bla:
def __init__(self, b):
self.a = b # add `b` as attribute `a`
def lol(self, c):
self.a = c # add `c` as attribute `a` (discarding previous values)
def rofl(self, d):
self.a += d # re-assign `self.a + d` as attribute `a`
# external function modifying `Bla` instance
def jk(bla, e):
bla.a = e # add `e` as attribute `a` (discarding previous values)
TA贡献1790条经验 获得超9个赞
我不确定 Bla.lol() 如何修改提供给它的参数 a,但它可以更改属性 Bla.a或self.a从对象内部引用它,该对象最初具有a分配给它的参数值。
我们可以让函数lol为属性分配一个新值a,在这种情况下,我将假设a它是一个字符串,并使用以下短语扩展该字符串' has been altered':
>>> class Bla:
... def __init__(self, a):
... self.a = a
...
... def lol(self):
... self.a += ' has been altered'
...
>>> instance = Bla('the arg a')
>>> instance.a # check a
'the arg a'
>>> instance.lol() # modifies a
>>> instance.a # check a again
'the arg a has been altered'
>>> instance.lol() # we can alter it again, as many times as we run the function
>>> instance.a # and see it has been altered a second time
'the arg a has been altered has been altered'
添加回答
举报