第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

Python 新手 - 為什么 self._ 在 Python 3 中導致 NameError

Python 新手 - 為什么 self._ 在 Python 3 中導致 NameError

holdtom 2022-10-25 16:06:02
我正在嘗試學習如何在 Python 中使用類,并通過反復試驗設法使以下代碼工作,但不知道如何!似乎使用了“自我”。有時需要,而在其他時候使用它會產(chǎn)生錯誤。我將非常感謝有人能解釋為什么不同的代碼行看起來如此不同如果我self._tot += _new用self._tot += self._newthen 替換該行,則會收到以下錯誤NameError: name 'self' is not defined。相反,如果我將行替換為self._tot -= self._lastthenself._tot -= _last我會收到以下錯誤NameError: name '_last' is not defined以這種看似相反的方式表現(xiàn)的代碼是:-class PremiumCounter:       def __init__(self, _tot = 0):        self._tot = _tot                self._new = 0        #self._last = 0    def add(self, _new = 1):        self._tot += _new        self._last = _new    def undo(self):        self._tot -= self._last           def get_total(self):        return self._tot    def clear_counter(self):        self._tot = 0ConcertAttendee2 = PremiumCounter(4)#Creates ConcertAttendee2 as an instance of the 'ImprovedCounter' classConcertAttendee2.clear_counter()ConcertAttendee2.add(3)ConcertAttendee2.add(3)ConcertAttendee2.undo()print("Total concert attendees: " + str(ConcertAttendee2.get_total() ))
查看完整描述

1 回答

?
BIG陽

TA貢獻1859條經(jīng)驗 獲得超6個贊

正如@jonrsharpe 指出的那樣,在您的undo方法中,您沒有名為 的參數(shù)_last,因此您會收到self._tot -= _last.


如果從函數(shù)參數(shù)中self._tot += _new with self._tot += self._new刪除,您可能會收到錯誤消息。self


此外,python 約定:對類屬性使用下劃線,而不是對參數(shù)使用下劃線。下面的代碼在命名約定方面更好。


class PremiumCounter:   


    def __init__(self, tot = 0):

        self._tot = tot        

        self._new = 0

        #self._last = 0


    def add(self, new = 1):

        self._tot += new

        self._last = new


    def undo(self):

        self._tot -= self._last       


    def get_total(self):

        return self._tot


    def clear_counter(self):

        self._tot = 0


查看完整回答
反對 回復 2022-10-25
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號