📜  Python delattr()函数

📅  最后修改于: 2022-05-13 01:54:36.281000             🧑  作者: Mango

Python delattr()函数

Python delattr()函数用于从类中删除属性。它有两个参数,第一个是我们要删除的类对象,第二个是我们要删除的属性的名称。

句法

delattr (object, name)  

参数

Parameter

Description

object

An object from which we want to delete the attribute

name

The name of the attribute we want to delete

delattr() 方法返回一个复数。

示例 1:

使用属性名称、持续时间、价格、评级创建课程。创建了一个类的实例,现在我们使用 delattr() 方法删除rating属性。最后,我们检查rating属性是否存在。一个 try 块用于处理 keyError

Python3
class course:
    name = "data structures using c++"
    duration_months = 6
    price = 20000
    rating = 5
 
# creating an object of course
print(course.rating)
 
# deleting the rating attribute from object
delattr(course, 'rating')
 
# checking if the rating attribute is there or not
try:
    print(course.rating)
except Exception as e:
    print(e)


Python3
class course:
    name = "data structures using c++"
    duration_months = 6
    price = 20000
    rating = 5
 
 
# creating an object of course
print(course.price)
 
# deleting the price attribute from object
delattr(course, 'price')
 
# checking if the price attribute is there or not
try:
    print(course.price)
except Exception as e:
    print(e)


输出
5
type object 'course' has no attribute 'rating'

示例 2:

使用属性名称、持续时间、价格、评级创建课程。创建了一个类的实例,现在我们使用 delattr() 方法删除价格属性。最后,我们检查价格属性是否存在。一个 try 块用于处理 keyError

Python3

class course:
    name = "data structures using c++"
    duration_months = 6
    price = 20000
    rating = 5
 
 
# creating an object of course
print(course.price)
 
# deleting the price attribute from object
delattr(course, 'price')
 
# checking if the price attribute is there or not
try:
    print(course.price)
except Exception as e:
    print(e)
输出
20000
type object 'course' has no attribute 'price'