Python 3 hasattr (), getattr(), setattr(), delattr() functions

Keywords: Python Attribute

  • hasattr() function

The hasattr() function is used to determine whether the corresponding attribute is included or not.

Syntax:

  hasattr(object,name)

Parameters:

object -- object

Name -- string, attribute name

Return value:

If the object has this attribute, it returns True, otherwise it returns False.

Example:

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'))
#Return value: True
print('country' in People.__dict__)
#Return value: True
print(hasattr(obj,'people_info'))
#Return value: 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() function

Description:

The getattr() function is used to return an object property value

Syntax:

  getattr(object,name,default)

Parameters:

object -- object

name -- String, Object Properties

Default -- The default return value, if not provided, triggers AttributeError in the absence of attributes.

Return value:

Returns object attribute values

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)
#Return value China
#obj=getattr(People,'countryaaaaaa')
#print(obj)
#Report errors
# File "/getattr()function.py", line 32, in <module>
#     obj=getattr(People,'countryaaaaaa')
# AttributeError: type object 'People' has no attribute 'countryaaaaaa'
obj=getattr(People,'countryaaaaaa',None)
print(obj)
#Return value None
  • setattr() function

Description:

The setattr function, which is used to set the property value, must exist

Syntax:

  setattr(object,name,value)

Parameters:

object -- object

name -- String, Object Properties

Value -- attribute value

Return value:

No

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) #Equate to 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() function

Description:

The delattr function is used to delete attributes

delattr(x,'foobar) is equivalent to del x.foobar

Syntax:

  setattr(object,name)

Parameters:

object -- object

name -- must be an attribute of an object

Return value:

No

Example:

class People:
    country='China'
    def __init__(self,name):
        self.name=name

    def people_info(self):
        print('%s is xxx' %(self.name))

delattr(People,'country') #Equivalent to 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}

Supplementary examples:

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()

Posted by Nakor on Tue, 05 Feb 2019 09:57:16 -0800