0
0

More than 1 year has passed since last update.

class内のdelattr(self,'xxxx')では自身のプロパティを消してくれない罠

Posted at

今回は軽い発見があったので、備忘録として書き込みます。

以下のコードを見ていて気づかなかったのだが、
このdelattrでは、プロパティは消えてくれない。

class Hoge(object):
    
    huga = 'hugahuga'

    def del_propaty(self):
        delattr(self, 'huga')

>>> hoge = Hoge()
>>> print(getattr(hoge,'huga'))
hugahuga
>>> hoge.del_propaty()

Traceback (most recent call last):
  File "/usr/lib/python3.9/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<input>", line 5, in del_propaty
AttributeError: huga

>>> print(getattr(hoge,'huga'))
hugahuga

このstockoverflowで確認すると、以下のようにself.__class__としないといけないようです。
↓以下修正したコード

class Hoge(object):
    
    huga = 'hugahuga'

    def del_propaty(self):
        delattr(self.__class__, 'huga')
>>> hoge = Hoge()
>>> print(getattr(hoge,'huga'))
hugahuga
>>> hoge.del_propaty()
# エラー出ず、getattrでも取れなくなっていました。
>>> print(getattr(hoge,'huga'))
Traceback (most recent call last):
  File "/usr/lib/python3.9/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
AttributeError: 'Hoge' object has no attribute 'huga'

以上です。
小さい発見ですが、またちょっとpythonを知れたそんな気分でした。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0