Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码数

枫铃3年前 (2021-09-30)Python215

hasattr()函数

hasattr()函数用于判断是否包含对应的属性

语法:

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('aaa')
print(hasattr(People,'country'))
#返回值:True
print('country' in People.__dict__)
#返回值:True
print(hasattr(obj,'people_info'))
#返回值:True
print(People.__dict__)
##{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10205d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}

getattr()函数

描述:

getattr()函数用于返回一个对象属性值

语法:

getattr(object,name,default)

参数:

  • object–对象

  • name–字符串,对象属性

  • default–默认返回值,如果不提供该参数,在没有对于属性时,将触发AttributeError。

返回值:

返回对象属性值

示例:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class People:
  country='China'
  def __init__(self,name):
    self.name=name
 
  def people_info(self):
    print('%s is xxx' %(self.name))
obj=getattr(People,'country')
print(obj)
#返回值China
#obj=getattr(People,'countryaaaaaa')
#print(obj)
#报错
# File "/getattr()函数.py", line 32, in <module>
#   obj=getattr(People,'countryaaaaaa')
# AttributeError: type object 'People' has no attribute 'countryaaaaaa'
obj=getattr(People,'countryaaaaaa',None)
print(obj)
#返回值None

setattr()函数

描述:

setattr函数,用于设置属性值,该属性必须存在

语法:

setattr(object,name,value)

参数:

  • object–对象

  • name–字符串,对象属性

  • value–属性值

返回值:

示例:

class People:
  country='China'
  def __init__(self,name):
    self.name=name
  def people_info(self):
    print('%s is xxx' %(self.name))
obj=People('aaa')
setattr(People,'x',111) #等同于People.x=111
print(People.x)
#obj.age=18
setattr(obj,'age',18)
print(obj.__dict__)
#{'name': 'aaa', 'age': 18}
print(People.__dict__)
#{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1007d5620>, 'people_info': <function People.people_info at 0x10215d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'x': 111}

delattr()函数

描述:

delattr函数用于删除属性

delattr(x,'foobar)相当于del x.foobar

语法:

setattr(object,name)

参数:

  • object–对象

  • name–必须是对象的属性

返回值:

示例:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class People:
  country='China'
  def __init__(self,name):
    self.name=name
  def people_info(self):
    print('%s is xxx' %(self.name))
delattr(People,'country') #等同于del People.country
print(People.__dict__)
{'__module__': '__main__', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10073d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': 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()

相关文章

利用python同步windows和linux文件

写python脚本的初衷,每次在windows编辑完文件后,想同步到linux上去,只能够登录服务器,...

爬虫基本原理

爬虫基本原理 一、爬虫是什么? 百度百科和维基百科对网络爬虫的定义:简单来说爬虫就是抓取目标网站内容的工具,一般是根据定义的行...

Django 函数和方法的区别

函数和方法的区别 1、函数要手动传self,方法不用传 2、如果是一个函数,用类名去调用,如果是一个方法...

Django 知识补漏单例模式

单例模式:(说白了就是)创建一个类的实例。在 Python 中,我们可以用多种方法来实现单例模式&#x...

Django基础知识MTV

Django简介 Django是使用Python编写的一个开源Web框架。可以用它来快速搭建一个高性能的网站。 Django也是一个MVC框架。但是在Dj...

Python mysql 索引原理与慢查询优化

一 介绍 为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。