【问题标题】:Object Oriented in Python 3: AttributesPython 3 中的面向对象:属性
【发布时间】: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


    【解决方案1】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      相关资源
      最近更新 更多