Which is better in python, del or delattr?

2019-01-21 01:21发布

This may be silly, but it's been nagging the back of my brain for a while.

Python gives us two built-in ways to delete attributes from objects, the del command word and the delattr built-in function. I prefer delattr because it I think its a bit more explicit:

del foo.bar
delattr(foo, "bar")

But I'm wondering if there might be under-the-hood differences between them.

标签: python del
8条回答
▲ chillily
2楼-- · 2019-01-21 01:46

It is an old question, but I would like to put my 2 cents in.

Though, del foo.bar is more elegant, at times you will need delattr(foo, "bar"). Say, if you have an interactive command line interface that allows a user to dynamically delete any member in the object by typing the name, then you have no choice but to use the latter form.

查看更多
Luminary・发光体
3楼-- · 2019-01-21 01:48

It's really a matter of preference, but the first is probably preferable. I'd only use the second one if you don't know the name of the attribute that you're deleting ahead of time.

查看更多
登录 后发表回答