欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

Python中hasattr(),getattr(),setattr()的用法介绍(代码示例)

程序员文章站 2022-04-04 23:29:25
...
本篇文章给大家带来的内容是关于Python中hasattr(),getattr(),setattr()的用法介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

1、hasattr(object, name)

  判断object里是否有name属性,有就返回True,没有则返回False。

class MyClass(object):
    name = 'jack'
    age = '22'


obj = MyClass()
print(hasattr(obj, 'name'))  # True
print(hasattr(MyClass, 'age'))  # True
print(hasattr(obj, 'gender'))  # False

2. getattr(object, name, [default])

用来获取object的属性或方法,有就打印出来. 没有就打印默认值,若是没有设置默认值则报错

class MyClass(object):
    name = 'jack'
    age = '22'

    def func(self):
        return 'hello world!!!'


obj = MyClass()

print(getattr(MyClass, 'name'))  # jack
print(getattr(obj, 'age'))  # 22
print(getattr(MyClass, 'func'))  # <function MyClass.func at 0x000001ACDE9A9AE8>
print(getattr(obj, 'func'))  # <bound method MyClass.func of <__main__.MyClass object at 0x000001D1505D01D0>>
# print(getattr(MyClass, 'func1'))  # 没有设置默认值,找不到方法会报错: AttributeError: type object 'MyClass' has no attribute 'func1'
print(getattr(MyClass, 'func1', None))  # 设置了默认值None,找不到就会返回默认值: None

print(getattr(MyClass, 'func')('self'))  # hello world!!!
print(getattr(obj, 'func')())  # hello world!!!

3. setattr(object, key, value)

用来对object的属性key赋值value. 若是key存在,则更新value的值. 若key不存在,则先创建属性key再对其赋值value.

class MyClass(object):
    name = 'jack'
    age = '22'


obj = MyClass()

setattr(MyClass, 'name', 'tom')
print(getattr(MyClass, 'name'))  # tom

setattr(obj, 'age', 28)
print(getattr(obj, 'age'))  # 28

setattr(MyClass, 'gender', 'male')
print(getattr(MyClass, 'gender'))  # male
print(getattr(obj, 'gender'))  # male

setattr(obj, 'hobby', 'skating')
print(obj, 'hobby')  # <__main__.MyClass object at 0x00000209F5070630> hobby
print(MyClass, 'hobby')  # <class '__main__.MyClass'> hobby

三个方法一起用:

class MyClass(object):
    name = 'jack'
    age = '22'


# 判断Myclass是否有gender属性,有则打印,没有则添加
def if_attr(gender='male'):
    if hasattr(MyClass, 'gender'):
        return getattr(MyClass, 'gender')
    return setattr(MyClass, 'gender', gender)


if_attr(gender='female')
print(getattr(MyClass, 'gender'))  # female

以上就是Python中hasattr(),getattr(),setattr()的用法介绍(代码示例)的详细内容,更多请关注其它相关文章!

相关标签: python