面向对象的Python 3:属性

时间:2017-09-06 10:10:10

标签: python

class Human:

    pass

stack = Human()
stack.name  #<- means? how to hide or kill or make to unusable **.name** ?

有人能帮助我吗?我可以在面向对象的Python中杀死这些未定义的属性。

1 个答案:

答案 0 :(得分:0)

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 ")

如果您的目的是删除属性,请使用以下方法:

方法1:使用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'

方法2:
 你可以使用delattr(Human, "name")

注1:方法1优于方法2,查看原因,更多详细信息请点击here