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'
添加回答
舉報