亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將某些東西添加到屬性中?

如何將某些東西添加到屬性中?

慕哥9229398 2022-06-28 11:08:07
如何修改或添加到類中?例如,在下面的代碼中,hello可以修改a我使用的 是什么意思__init__?我對 OOP 仍然有很多不確定性,尤其是實例化與其他事物之間的關系。我確信這是可能的;如果是這樣,我該怎么做?class Foo:    def __init__(self, a):        self.a = a         def hello(self):
查看完整描述

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)


查看完整回答
反對 回復 2022-06-28
?
富國滬深

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'


查看完整回答
反對 回復 2022-06-28
  • 2 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號