python hasattr()、getattr()、setattr()、delattr()函数

Python hasattr()、getattr()、setattr()、delattr()函数

hasattr()函数

hasattr()函数用于判断是否包含对应的属性;当然,对于Python的对象而言,属性包含变量和方法;有则返回True,没有则返回False;需要注意的是name参数是string类型,所以不管是要判断变量还是方法,其名称都已字符串形式传参;getattr和setattr也同样;

语法:

​ hasattr(object, name)

参数:

​ object – 对象

​ name – 字符串,属性名

返回值:

​ 如果对象有该属性返回True,否则返回False

示例:

class People:
    country = 'China'
    
    def __init__(self, name):
        self.name = name
       
    def people_info(self):
        print('%s is xxx' % self.name)
        
obj = People('zhangsan')

print(hasattr(People, 'country'))
# True

print(hasattr(People, 'language'))
# False

print('country' in People.__dict__)
# True

print(hasattr(obj, 'people_info'))
# True

print(People.__dict__)
"""
{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x0000029C736AAAE8>, 'people_info': <function People.people_info at 0x0000029C736AAB70>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
"""

getattr()函数

描述:

​ getattr()函数用于返回一个对象属性值;如果存在则返回属性值,如果不存在分为两种情况,一种是没有default参数时,会直接报错;给定了default参数,若对象本身没有name属性,则会返回给定的default值;如果给定的属性name是对象的方法,则返回的是函数对象,需要调用函数对象来获得函数的返回值;调用的话就是函数对象后面加括号,如people_info:people_info();

​ 另外还需要注意,如果给定的方法people_info()是实例函数,则不能写getattr(People, ‘people_info’)(),因为people_info()是实例函数的话,是不能用People类对象来调用的,应该写成getattr(People(), 'people_info')();实例函数和类函数的区别可以简单的理解一下,实例函数定义时,直接def people_info(self): pass;这样定义的函数只能是将类实例化后,用类的实例化对象来调用;而类函数定义时,需要用@classmethod来装饰,函数默认的参数一般是cls;类函数可以通过类对象来直接调用,而不需要对类进行实例化;

语法:

​ getattr(object, name, default)

参数:

​ object – 对象

​ name – 字符串,对象属性

​ default – 默认返回值,如果不提供该参数,在没有对应属性时,将抛出AttributeError。

返回值:

​ 返回对象属性值

示例:

class People:
    country = 'China'
    
    def __init__(self, name):
        self.name = name
    
    def people_info(self):
        print('%s is xxx' % self.name)
        
    @classmethod
    def func(cls):
        print('the method of A class.')

attr = getattr(People, 'country')
print(attr)
# China

attr = getattr(People, 'language')
"""
Traceback (most recent call last):
  File "E:/Python5/trainPro/myOwnSite/my_study/py_getattr_setattr.py", line 36, in <module>
    obj = getattr(People, 'language')
AttributeError: type object 'People' has no attribute 'language'
"""

attr = getattr(People, 'language', None)
print(attr)
# None

getattr(People, 'people_info')()
"""
Traceback (most recent call last):
  File "E:/Python5/trainPro/myOwnSite/my_study/py_getattr_setattr.py", line 42, in <module>
    getattr(People, 'people_info')()
TypeError: people_info() missing 1 required positional argument: 'self'
"""

getattr(People('zhangsan'), 'people_info')()
"""
zhangsan is xxx
"""

getattr(People, 'func')()
"""
the method of A class.
"""

setattr()函数

描述:

​ setattr函数,用于设置属性值,给object对象的name属性赋值value,如果对象原本存在给定的属性name,则setattr会更改属性的值为给定的value;如果对象原本不存在属性name,setattr会在对象中创建属性,并赋值为给定的value;

语法:

​ setattr(object, name, value)

参数:

​ object – 对象

​ name – 字符串,对象属性

​ value – 属性值

返回值

​ 无

示例:

class A:
    name = 'python'
    def func(self):
        print('Hello World!')

setattr(A, 'name', 'java')	# 等同于A.name = 'java'
name = getattr(A, 'name')
print(name)		# == print(A.name)
# java

setattr(A, 'age', 20)
age = getattr(A, 'age')
print(age)
# 20

obj = A()
setattr(obj, 'age', 18)
print(obj.age)
# 18
print(obj.__dict__)
{'age': 18}

print(A.__dict__)
"""
{'__module__': '__main__', 'name': 'java', 'func': <function A.func at 0x000002694158AD08>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None, 'age': 20}
"""

一般先判断对象中是否存在某属性,如果存在则返回;如果不存在,则给对象增加属性并赋值;很简单的if-else判断:

if hasattr(A, 'age'):
    print(getattr(A, 'age'))
else:
    setattr(A, 'age', 20)
    
# 20

delattr()函数

描述:

​ delattr函数用于删除属性

​ delattr(x, ‘foobar’)相当于del x.foobar

语法:

​ delattr(object, name)

参数:

​ object – 对象

​ name – 必须是对象的属性

返回值:

​ 无

示例:

class A:
    name = 'python'
    
    def __init__(self, age):
        self.age = age
    
    def func(self):
        print('Hello World!')
        
print(A.__dict__)
"""
{'__module__': '__main__', 'name': 'python', '__init__': <function A.__init__ at 0x000001F360AE00D0>, 'func': <function A.func at 0x000001F360AE0158>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
"""

delattr(A, 'name')	# 等同于 del A.name
print(A.__dict__)
"""
{'__module__': '__main__', '__init__': <function A.__init__ at 0x000001F360AE00D0>, 'func': <function A.func at 0x000001F360AE0158>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
"""

name = getattr(A, 'name', None)
print(name)
# None

补充示例:

class Foo:
    def run(self):
        while True:
            cmd=input('cmd>>: ').strip()
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func()

    def download(self):
        print('download....')

    def upload(self):
        print('upload...')

obj=Foo()
obj.run()
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值