Python hasattr() getattr() setattr() delattr()函数使用方法

(一) hasattr(object, name) 函数

判断一个对象里面是否有 name 属性或者 name 方法,返回 bool 值;如果有 name 属性(方法)则返回 True ,否则返回 False 。

注意: name方法名 需要使用引号括起来。

class Student:
    name = 'lisi'
    def study(self, subject):
        print(f'{self.name} is studying {subject}' )


s = Student()
print(hasattr(s, 'name'))
print(hasattr(s, 'study'))
print(hasattr(s, 'score'))
s.study('math

####################################################
C:\Users\zedking\AppData\Local\Programs\Python\Python310\python.exe D:/python/hasattr.py
True
True
False
lisi is studying math

Process finished with exit code 0

(二) getattr(object, name[, default])  函数

获取对象 object 的属性或者方法,若存在则打印出来;若不存在,则打印默认值,默认值可选。

注意:如果返回的是对象的方法,那么打印的结果是方法的内存地址。如果需要运行这个方法,那么可以在后面添加括号 () 。

class Student:
    name =  'lisi'
    def study(self, project):
        print(f'{self.name} is studying {project}' )
        return project


s = Student()
print(getattr(s, 'name'))  # 获取Student的name属性 存在就打印出来
print(getattr(s, 'study'))  # 获取Student的run方法,村子啊打印出方法的内存地址
print(getattr(s, 'study')('math'))
print(Student.study(Student, 'math'))
print(getattr(Student, 'study')(Student, 'math'))

print(getattr(s, 'score', 60)) #设置默认值60 如果没有该方法或者属性 则返回默认值

################################################################################
C:\Users\l23188\PycharmProjects\pythonProject\venv\Scripts\python.exe D:/python/getattr.py
lisi
<bound method Student.study of <__main__.Student object at 0x000001F5B9635FD0>>
lisi is studying math
math
lisi is studying math
math
lisi is studying math
math
60

Process finished with exit code 0

(三)setattr(object, name, values) 函数

给对象的属性赋值,若属性不存在,则先为该对象创建该属性再为对象属性赋值。

class Student:
    name = 'lisi'
    def study(self, project):
        print(f'{self.name} is studying {project}')
s = Student()

print(hasattr(Student, 'score'))
setattr(Student, 'score', 90)
print(hasattr(Student, 'score'))

#综合使用

if hasattr(s,'addr'):
    addr = s.addr
    print(addr)
else:
    addr = getattr(s, 'addr', setattr(s, 'addr', 'Chengdu'))
    print(addr)
    
###############################################################
C:\Users\l23188\PycharmProjects\pythonProject\venv\Scripts\python.exe D:/python/setattr.py
False
True
Chengdu

Process finished with exit code 0

 (四)delattr(object, name)函数

实例化的对象中属性是只读的,无法使用delattr执行删除操作。

class Student:
    name = 'lisi'
    age = 20
s = Student()

print(s.name)
delattr(Student, 'name')
delattr(s, 'age') #有报错 因为实例化后的对象不能够删除属性
print(s.name)

##############################################################
C:\Users\l23188\PycharmProjects\pythonProject\venv\Scripts\python.exe D:/python/delattr.py
lisi
Traceback (most recent call last):
  File "D:\python\delattr.py", line 8, in <module>
    delattr(s, 'age') #有报错 因为实例化后的对象不能够删除属性
AttributeError: age

Process finished with exit code 1

 

posted @ 2022-04-12 21:03  zed99  阅读(75)  评论(0编辑  收藏  举报