PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

不言
不言 原创
2018-04-18 11:10:41 1670浏览

本文通过示例代码给大家详细介绍了Python3 中hasattr()、getattr()、setattr()、delattr()函数,非常不错,具有参考借鉴价值,需要的朋友参考下吧

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__': , 'people_info': , '__dict__': , '__weakref__': , '__doc__': None}


getattr()函数

描述:

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

语法:

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))
obj=getattr(People,'country')
print(obj)
#返回值China
#obj=getattr(People,'countryaaaaaa')
#print(obj)
#报错
# File "/getattr()函数.py", line 32, in 
#   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__': , 'people_info': , '__dict__': , '__weakref__': , '__doc__': None, 'x': 111}


delattr()函数

描述:

delattr函数用于删除属性

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

语法:

setattr(object,name)

参数:

object--对象

name--必须是对象的属性

返回值:

示例:


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__': , 'people_info': , '__dict__': , '__weakref__': , '__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()

相关推荐:

python3库numpy数组属性的查看方法


以上就是Python3 中hasattr()、getattr()、setattr()、delattr()函数及示例代码的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。