Style question - defining immutable class data members

M

Maxim Khitrov

Very simple question on the preferred coding style. I frequently write
classes that have some data members initialized to immutable values.
For example:

class Test(object):
def __init__(self):
self.some_value = 0
self.another_value = None

Similar effect can be achieved by defining some_value and
another_value for the entire class, like so:

class Test(object):
some_value = 0
another_value = None

The advantage of doing this is that the assignments are evaluated once
and thus the creation of that class is a bit faster. Access is still
performed through self.some_value and self.another_value. Is there a
reason to prefer the first style over the second?

- Max
 
A

Aahz

Very simple question on the preferred coding style. I frequently write
classes that have some data members initialized to immutable values.
For example:

class Test(object):
def __init__(self):
self.some_value = 0
self.another_value = None

Similar effect can be achieved by defining some_value and
another_value for the entire class, like so:

class Test(object):
some_value = 0
another_value = None

The advantage of doing this is that the assignments are evaluated once
and thus the creation of that class is a bit faster. Access is still
performed through self.some_value and self.another_value. Is there a
reason to prefer the first style over the second?

Well, as you can see from reading this whole thread, it can be the source
of some confusion. Nevertheless, I personally sometimes use the style of
initializing at the class level. I think it's probably worth creating a
style guide entry for this issue if you're using Python for your
employer.
--
Aahz ([email protected]) <*> http://www.pythoncraft.com/

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-3-22
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top