python logo

Python Commandments

Python hashattr method

The hasattr() function is used to determine if the object contains the corresponding property.

Everything in python is an object. The four related functions:

  • hasattr: determines if this variable is present, returns the bool value
  • getattr: Get the property value or get the address of the method variable
  • setattr: Set properties or methods for classes or objects
  • delattr: Deletes attributes or methods of classes or objects

You can use them on:

  • Properties and methods of classes
  • Properties and methods of objects
  • Properties and methods of module

syntax

hasattr Syntax.

hasattr(object, name)

parameters

  • object – object.
  • name – string, attribute name.

return value

  • Returns True if the object has this property, False otherwise.

hashattr example

The following example shows how hasattr is used:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Coordinate:
    x = 10
    y = -5
    z = 0

point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no'))# No this property

Outputs.

True
True
True
False

getattr example

getattr(), as the name implies, gets the property of the object, getattr(x, ‘y’) is equivalent to x.y.

The third argument is dispensable, when the third argument is given to getattr(), if the corresponding property does not exist, it is returned as a return value.

Look at the following code.

class Test(object):
     val = 1

>>> Test.val
1
>>> getattr(Test, 'val')
1
>>> getattr(Test, 'va', 5)
5

setattr example

Set the value of an object attribute, which is automatically created when it does not exist

class test():
    a=1
    b=2

if __name__ == '__main__':
    t=test()
    print(getattr(t,'a'))
    setattr(t,'a','a')
    print(getattr(t, 'a'))
    setattr(t, 'ab', 'ab')
    print(getattr(t, 'ab'))

delattr example

Remove the name attribute from the object object.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

tom = Person("Tom", 35)
print dir(tom)
delattr(tom, "age")
print dir(tom)