4

Refer to the following code as an example:

import numpy as np

N = 200
some_prop = np.random.randint(0,100, [N, N, N])

#option 1
class ObjectThing():
  def __init__(self, some_prop):
    self.some_prop = some_prop


object_thing = ObjectThing(some_prop)



#option 2
pseudo_thing = {'some_prop' : some_prop }

I like the structure that option 1 provides, it makes the operation of an application more rigid and whatnot. However, I'm wondering if there are other more absolute benefits that I'm not aware of.

RodericDay
  • 1,266
  • 4
  • 20
  • 35

2 Answers2

1

If you're using an implementation of Python that includes a JIT compiler (e.g. PyPy), using actual objects can improve the compiler's ability to optimize your code (because it's easier for the compiler to reason about how members of an object are utilized, unlike a plain dictionary).

Using objects also allows for subclassing, which can save some redundant implementation.

Amber
  • 507,862
  • 82
  • 626
  • 550
1

The obvious advantage of using objects is that you can extend their functionality beyond simply storing data. You could, for instance, have two attributes, and define and __eq__ method that uses both attributes in some way other than simply comparing both of them and returning False unless both match.

Also, once you've got a class defined, you can easily define new instances of that class that will share the structure of the original, but with a dictionary, you'd either have to redefine that structure or make a copy of some sort of the original and then change each element to match the values you want the new pseudo-object to have.

The primary advantages of dictionaries are that they come with a variety of pre-defined methods (such as .items()), can easily be iterated over using in, can be conveniently created using a dict comprehension, and allow for easy access of data "members" using a string variable (though really, the getattr function achieves the same thing with objects).

Kyle Strand
  • 15,941
  • 8
  • 72
  • 167