【发布时间】:2017-09-06 10:10:09
【问题描述】:
class Human:
pass
stack = Human()
stack.name #<- means? how to hide or kill or make to unusable **.name** ?
有人可以帮助我吗?我可以在 Python 的面向对象中杀死这些未定义的属性吗?
【问题讨论】:
标签: python
class Human:
pass
stack = Human()
stack.name #<- means? how to hide or kill or make to unusable **.name** ?
有人可以帮助我吗?我可以在 Python 的面向对象中杀死这些未定义的属性吗?
【问题讨论】:
标签: python
class Human():
pass
m1 = Human()
try:
m1.name
except AttributeError:
pass # for hiding this error or you can use (print "this attribute does not exist ")
如果您的预期目的是删除属性,请使用以下方法:
方法一:使用del
>>> class Human():
def __init__(self,name,lastname):
self.name = name
self.lastname = lastname
>>> m1 = Human('name' , 'lastname')
删除前
>>> m1.name
'name'
>>> del m1.name
删除后
>>> m1.name
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
m1.name
AttributeError: Human instance has no attribute 'name'
方法二:
你可以使用delattr(Human, "name")
注意 1 :方法 1 比方法 2 更好,请参阅为什么,更多详情请点击here
【讨论】: