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() and del()用法及代码示例
- Python Tkinter destroy()用法及代码示例
- Python degrees() and radians()用法及代码示例
- Python dict()用法及代码示例
- Python datetime astimezone()用法及代码示例
- Python datetime timetuple()用法及代码示例
- Python datetime timetz()用法及代码示例
- Python dictionary values()用法及代码示例
- Python datetime isocalendar()用法及代码示例
- Python date toordinal()用法及代码示例
- Python dir()用法及代码示例
- Python date replace()用法及代码示例
- Python date strftime()用法及代码示例
- Python datetime date()用法及代码示例
- Python datetime isoformat()用法及代码示例
- Python divmod()用法及代码示例
- Python datetime __str__()用法及代码示例
- Python date weekday()用法及代码示例
- Python date isoweekday()用法及代码示例
- Python datetime.timedelta()用法及代码示例
注:本文由纯净天空筛选整理自 Python delattr() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。