>  기사  >  백엔드 개발  >  Python3의 Hasattr(), getattr(), setattr(), delattr() 함수 및 샘플 코드

Python3의 Hasattr(), getattr(), setattr(), delattr() 함수 및 샘플 코드

不言
不言원래의
2018-04-18 11:10:411992검색

이 글은 Python3의 hasattr(), getattr(), setattr(), delattr() 함수를 샘플 코드를 통해 자세히 소개하고 있어 매우 좋고 참고할만한 가치가 있습니다.

hasattr() 함수

hasattr() 함수는 해당 속성이 포함되어 있는지 확인하는 데 사용됩니다.

구문:

hasattr(object,name)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__)
##{&#39;__module__&#39;: &#39;__main__&#39;, &#39;country&#39;: &#39;China&#39;, &#39;__init__&#39;: <function People.__init__ at 0x1006d5620>, &#39;people_info&#39;: <function People.people_info at 0x10205d1e0>, &#39;__dict__&#39;: <attribute &#39;__dict__&#39; of &#39;People&#39; objects>, &#39;__weakref__&#39;: <attribute &#39;__weakref__&#39; of &#39;People&#39; objects>, &#39;__doc__&#39;: None}


getattr()函数

描述:

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

语法:

getattr(object,name,default)

参数:

object--对象

name--字符串,对象属性

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

返回值:

返回对象属性值


class People:
  country=&#39;China&#39;
  def __init__(self,name):
    self.name=name

  def people_info(self):
    print(&#39;%s is xxx&#39; %(self.name))
obj=getattr(People,&#39;country&#39;)
print(obj)
#返回值China
#obj=getattr(People,&#39;countryaaaaaa&#39;)
#print(obj)
#报错
# File "/getattr()函数.py", line 32, in <module>
#   obj=getattr(People,&#39;countryaaaaaa&#39;)
# AttributeError: type object &#39;People&#39; has no attribute &#39;countryaaaaaa&#39;
obj=getattr(People,&#39;countryaaaaaa&#39;,None)
print(obj)
#返回值None


setattr()函数

描述:

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

语法:

setattr(object,name,value)

参数:

object--对象

name--字符串,对象属性

value--属性值

返回值:


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


delattr()函数

描述:

delattr函数用于删除属性

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

语法:

setattr(object,name)

매개변수:

object-- object

name- -String, 속성 이름

반환 값:

객체에 이 속성이 있으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

예:


class People:
  country=&#39;China&#39;
  def __init__(self,name):
    self.name=name
  def people_info(self):
    print(&#39;%s is xxx&#39; %(self.name))
delattr(People,&#39;country&#39;) #等同于del People.country
print(People.__dict__)
{&#39;__module__&#39;: &#39;__main__&#39;, &#39;__init__&#39;: <function People.__init__ at 0x1006d5620>, &#39;people_info&#39;: <function People.people_info at 0x10073d1e0>, &#39;__dict__&#39;: <attribute &#39;__dict__&#39; of &#39;People&#39; objects>, &#39;__weakref__&#39;: <attribute &#39;__weakref__&#39; of &#39;People&#39; objects>, &#39;__doc__&#39;: None}


getattr() 함수


설명: getattr() 함수는 객체 속성 값을 반환하는 데 사용됩니다

구문: ​​

getattr(object,name,default)매개변수:

object--object

name--string , Object 속성 🎜🎜default--기본 반환 값입니다. 이 매개변수가 제공되지 않으면 속성이 없을 때 AttributeError가 발생합니다. 🎜🎜반환 값: 🎜🎜객체 속성 값 반환 🎜🎜🎜🎜
class Foo:
  def run(self):
    while True:
      cmd=input(&#39;cmd>>: &#39;).strip()
      if hasattr(self,cmd):
        func=getattr(self,cmd)
        func()
  def download(self):
    print(&#39;download....&#39;)
  def upload(self):
    print(&#39;upload...&#39;)
# obj=Foo()
# obj.run()
🎜🎜🎜🎜🎜🎜setattr() 함수 🎜🎜🎜🎜설명: 🎜🎜setattr 함수, 속성 값을 설정하는 데 사용됨, 속성이 존재해야 함 🎜🎜 구문 :🎜🎜setattr(객체, 이름, 값)🎜🎜매개변수: 🎜🎜객체--객체 🎜🎜이름--문자열, 객체 속성 🎜🎜값-속성 값 🎜🎜반환 값: 🎜🎜None🎜🎜🎜🎜rrreee🎜🎜🎜🎜🎜🎜delattr() function🎜🎜🎜🎜설명: 🎜🎜delattr 함수는 속성을 삭제하는 데 사용됩니다.🎜🎜delattr(x,'foobar)는 del x.f와 동일합니다. 우바🎜 🎜Grammar :🎜🎜setattr(object,name)🎜🎜매개변수: 🎜🎜object--객체 🎜🎜name--객체의 속성이어야 합니다 🎜🎜반환 값: 🎜🎜None 🎜🎜 예: 🎜🎜 🎜🎜rrreee🎜🎜🎜🎜보충 예: 🎜🎜🎜🎜rrreee🎜🎜🎜🎜🎜관련 권장 사항: 🎜🎜🎜python3 라이브러리에서 numpy 배열 속성을 보는 방법🎜🎜🎜 🎜🎜

위 내용은 Python3의 Hasattr(), getattr(), setattr(), delattr() 함수 및 샘플 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.