Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring members only in constructor

I'm coming from a C++ background to python

I have been declaring member variables and setting them in a C++esqe way like so:

class MyClass:
    my_member = []

    def __init__(self,arg_my_member):
        self.my_member = arg_my_member

Then I noticed in some open source code, that the initial declaration my_member = [] was completely left out and only created in the constructor.

Which obviously is possible as python is dynamic.

My question is, is this the preferred or Pythonic way of doing things, and are there and pros and cons of either?

like image 506
zenna Avatar asked Jul 24 '10 10:07

zenna


1 Answers

The way you are doing it means that you'll now have a "static" member and a "non-static" member of the same name.

class MyClass:
    my_member = []

    def __init__(self, arg_my_member):
        self.my_member = arg_my_member


>>> a = MyClass(42)
>>> print a.my_member
42
>>> print MyClass.my_member
[]
like image 75
UncleBens Avatar answered Oct 27 '22 09:10

UncleBens