python hasattr()、getattr()、setattr()

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值