当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python delattr()用法及代码示例

Python delattr() 函数用于从类中删除属性。它需要两个参数,第一个是类的对象,第二个是我们要删除的属性。删除该属性后,它在类中不再可用,如果尝试使用类对象调用它,则会引发错误。

签名

delattr (object, name)

参数

object:包含属性的类的对象。

name:要删除的属性的名称。它必须是一个字符串。

返回

它返回一个复数。

让我们看一些 delattr() 函数的例子来理解它的函数。

Python delattr() 函数示例 1

这是一个简单的例子,包含一个 Student 类,通过使用 delattr() 函数,我们将删除它的 email 属性。

# Python delattr() function example
class Student:
    id = 101
    name = "Rohan"
    email = "rohan@abc.com"
    def getinfo(self):
        print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'email') # Removing attribute
s.getinfo() # error:no attribute 'email' is available

输出:

AttributeError:'Student' object has no attribute 'email'
101 Rohan [email protected]

Python delattr() 函数示例2

如果我们删除一个不存在的属性,它会抛出一个错误。

# Python delattr() function example
class Student:
    id = 101
    name = "Rohan"
    email = "rohan@abc.com"
# Declaring function
    def getinfo(self):
        print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error:throws an error

输出:

AttributeError:course






相关用法


注:本文由纯净天空筛选整理自 Python delattr() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。