hasattr(object, name)
判断object对象中是否存在name属性。对于python的对象而言,属性包含变量和方法。有则返回True,没有则返回False。无论属性是变量还是方法,name都是str类型的
class Student():
name = 'xiaoming'
def func(self):
return 'This is a student'
print(hasattr(Student,'name'))
print(hasattr(Student,'func'))
print(hasattr(Student,'gender'))
True
True
False
getattr(object, name, default=None)
获取object对象的属性的值,如果存在就返回该属性的值。如果不存在,分两种情况。第一种是未设置default,会报错提示不存在;第二种是设置了default,会返回default的值。
class Student():
name = 'xiaoming'
def func(self):
return 'This is a student'
print(getattr(Student,'name'))
print(getattr(Student,'score',0)) #设置了默认值,不存在返回默认值
print(getattr(Student,'gender')) #未设置默认值,不存在会报错
Traceback (most recent call last):
xiaoming
0
File "F:/studycode/code.py", line 7, in <module>
print(getattr(Student, 'gender'))
AttributeError: type object 'Student' has no attribute 'gender'
通过getattr也可获取函数对象,然后再调用函数对象获得函数返回值,但根据函数对象的类型传入的object也不同。若函数为类方法,则可直接传入类名;若函数为实例方法,则需要传入类的实例,才可调用返回的函数对象。
class Student():
name = 'xiaoming'
def func1(self):
return 'This is a student'
@classmethod
def func2(self):
return 'This is a class'
print(getattr(Student,'func1'))
print(getattr(Student,'func2')())
print(getattr(Student(),'func1')())
<function Student.func1 at 0x0332AA50>
This is a class
This is a student
setattr(object, name, value)
给object对象的name属性赋值value,如果对象原本存在给定的属性name,则setattr会更改属性的值为给定的value;如果对象原本不存在属性name,setattr会在对象中创建属性,并赋值为给定的value
class Student():
name = 'xiaoming'
def func1():
return 'hello'
def func2():
return 'object'
setattr(Student, 'name', 'setattr')
print(getattr(Student,'name'))
setattr(Student, 'age', 19)
print(getattr(Student,'age'))
setattr(Student, 'func1', func1)
print(getattr(Student,'func1')())
s = Student() # 如果要设置实例函数,必须先在外面实例化一个对象,不然get和set的是两个不同的实例。
setattr(s, 'func2',func2)
print(getattr(s,'func2')())
setattr
19
hello
object