python函式每日一講 - delattr(object, name)

pythontab發表於2013-02-25

delattr(object, name)

中文說明:刪除object物件名為name的屬性。這個函式的命名真是簡單易懂啊,和jquery裡面差不多,但是功能不一樣哦,注意一下。

引數object:物件。

引數name:屬性名稱字串。

版本:各版本中都支援該函式,python3中仍可用。

英文說明:This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del x.foobar.

程式碼例項:

>>> class Person:
...     def __init__(self, name, age):
...             self.name = name
...             self.age = age
...
>>> tom = Person("Tom", 35)
>>> dir(tom)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> delattr(tom, "age")
>>> dir(tom)
['__doc__', '__init__', '__module__', 'name']

相關文章