Python怎么删除对象属性?

1 个回答|146 次阅读
Coco老师 - 公众号:量位学堂Qbit编程
擅长:编程教育
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  def myfunc(self):
    print("我的名字是 " + self.name)
p1 = Person("小花", 36)
del p1.name #删除name属性
p1.myfunc()

执行结果:报错name属性不存在,说明删除成功了

Traceback (most recent call last):
File "d:\users\xingc\desktop\7.py", line 9, in <module>
p1.myfunc()
File "d:\users\xingc\desktop\7.py", line 6, in myfunc
print("我的名字是 " + self.name)
AttributeError: 'Person' object has no attribute 'name'