Friday, August 25, 2023
HomeProgrammingGet All Object Attributes in Python

Get All Object Attributes in Python


Introduction

In Python, every thing is an object – from integers and strings to courses and features. 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 mainly juset properties or traits that assist outline the item.

On this Byte, we’ll discover other ways to get all attributes of an object in Python, and the way to show and manipulate them successfully.

Viewing Object Attributes

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

Contemplate a easy class, Firm, with a couple of attributes:

class Firm:
    def __init__(self, identify, trade, num_employees):
        self.identify = identify
        self.trade = trade
        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’ll be able to see, dir() returns not solely the attributes we outlined (i.e. identify, trade, num_employees), but in addition an inventory of particular strategies (also called dunder strategies) inherent to all Python objects.

Getting their Values

Now that we all know the way to get the attributes of an object, let’s have a look at the way to additionally extract their values. Python gives a built-in operate, getattr(), which permits us to get the worth of a selected 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’ll be able to present a 3rd argument to getattr(), which will probably be returned if the attribute is just not discovered, thus avoiding the error:

location = getattr(c, 'location', 'Not out there')
print(location)

This can output:

Not out there

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

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 item’s attributes to their respective values. This may be very useful after we wish to extract all properties and values of an object. Let’s have a look at the way it works.

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

While you run the above code, it is going to output:

{'attr1': 'Hi there', 'attr2': 'World'}

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

Formatting Object Attributes into Strings

Typically it’s possible 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 attain this. This is how you are able to do it:

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

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

While you run the above code, it is going to output:

"{'attr1': 'Hi there', 'attr2': 'World'}"

Using vars() for Attribute Extraction

One other solution 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 = 'Hi there'
        self.attr2 = 'World'
        
occasion = TestClass()
print(vars(occasion))

While you run the above code, it is going to output:

{'attr1': 'Hi there', 'attr2': 'World'}

Be aware: 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 gives quite a lot of instruments to extract and manipulate object attributes.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments