Saturday, March 30, 2024

Get All Object Attributes in Python

Must read


Introduction

In Python, every thing is an object – from integers and strings to lessons and capabilities. This will appear odd, particularly for primitive varieties like numbers, however even these have attributes, like actual and imag. Every object has its personal attributes, that are principally juset properties or traits that assist outline the article.

On this Byte, we are going to discover other ways to get all attributes of an object in Python, and how you can show and manipulate them successfully.

Viewing Object Attributes

To start out with, let us take a look at how we will view the attributes of an object in Python. Python offers a built-in operate, dir(), which returns a listing of all attributes and strategies of an object, which additionally contains these inherited from its class or mum or dad lessons.

Take into account a easy class, Firm, with a couple of attributes:

class Firm:
    def __init__(self, identify, business, num_employees):
        self.identify = identify
        self.business = business
        self.num_employees = num_employees

Now, let’s create an occasion of Firm and use dir() to get its attributes:

c = Firm('Dunder Mifflin', 'paper', 15)
print(dir(c))

This can output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'industry', 'num_employees', 'name']

As you may see, dir() returns not solely the attributes we outlined (i.e. identify, business, num_employees), but additionally a listing of particular strategies (also called dunder strategies) inherent to all Python objects.

Getting their Values

Now that we all know how you can get the attributes of an object, let’s examine how you can additionally extract their values. Python offers a built-in operate, getattr(), which permits us to get the worth of a particular attribute.

This is how you need to use getattr():

identify = getattr(c, 'identify')
print(identify)

This can output:

Dunder Mifflin

On this instance, getattr() returns the worth of the identify attribute of the Firm occasion c. If the attribute doesn’t exist, getattr() will elevate an AttributeError. Nevertheless, you may present a 3rd argument to getattr(), which shall be returned if the attribute is just not discovered, thus avoiding the error:

location = getattr(c, 'location', 'Not obtainable')
print(location)

This can output:

Not obtainable

On this case, since location is just not an attribute of c, getattr() returns the offered default worth, ‘Not obtainable’.

Utilizing __dict__ to get Properties and Values

In Python, each object is supplied with a __dict__ attribute. This built-in attribute is a dictionary that maps the article’s attributes to their respective values. This may be very useful once we wish to extract all properties and values of an object. Let’s examine the way it works.

class TestClass:
    def __init__(self):
        self.attr1 = 'Howdy'
        self.attr2 = 'World'
        
occasion = TestClass()
print(occasion.__dict__)

Whenever you run the above code, it can output:

{'attr1': 'Howdy', 'attr2': 'World'}

Observe: __dict__ doesn’t return strategies of an object, solely the properties and their values.

Formatting Object Attributes into Strings

Generally chances are you’ll wish to format the attributes of an object right into a readable string for show or logging functions. Python’s built-in str operate might be overridden in your class to realize this. This is how you are able to do it:

class TestClass:
    def __init__(self):
        self.attr1 = 'Howdy'
        self.attr2 = 'World'

    def __str__(self):
        return str(self.__dict__)
        
occasion = TestClass()
print(str(occasion))

Whenever you run the above code, it can output:

"{'attr1': 'Howdy', 'attr2': 'World'}"

Using vars() for Attribute Extraction

One other approach to extract attributes from an object in Python is by utilizing the built-in vars() operate. This operate behaves similar to the __dict__ attribute and returns the __dict__ attribute of an object. This is an instance:

class TestClass:
    def __init__(self):
        self.attr1 = 'Howdy'
        self.attr2 = 'World'
        
occasion = TestClass()
print(vars(occasion))

Whenever you run the above code, it can output:

{'attr1': 'Howdy', 'attr2': 'World'}

Observe: Like __dict__, vars() additionally doesn’t return strategies of an object, solely the properties and their values.

Conclusion

Getting the entire attributes of an object in Python might be achieved in a number of methods. Whether or not you are utilizing dir(), the __dict__ attribute, overriding the str operate, or utilizing the vars() operate, Python offers quite a lot of instruments to extract and manipulate object attributes.



Supply hyperlink

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article