Cantfindname
Cantfindname

Reputation: 2148

Changing class variable: good practice or not? (Python)

I have a class Foo, containing a class variable size. I want to calculate the size the first time I create a Foo object and use the same for all subsequent objects, but not calculate the size again. For the sake of containing everything within the Foo class I came up with this code:

class Foo(object):
    size = -1
    def __init__(self,args):
        if Foo.size < 0:
            Foo.size = some_calculation(args)

In my small tests, it does what I want. However, is this considered good practice? Is there a better way to do it?

Upvotes: 3

Views: 1051

Answers (1)

Pynchia
Pynchia

Reputation: 11586

This is by no means an exhaustive answer, but I would like to point out something I cannot describe easily in a comment.

As said in the comments, there's nothing wrong with your approach. It depends on what you want to do.

Let me point out that in case in the future you end up defining a subclass which calculates size according to a different rule/initial value, it may be useful to refer to it via self. (instead of reaching it via the class' name)

e.g.

>>> class A:
...  size=1
...  def printsize(self):
...   print(self.size)
... 
>>> class B(A):
...  size=2
... 
>>> a=B()
>>> a.printsize()
2

Upvotes: 1

Related Questions