Reputation: 11228
I come from Java, so I'm getting confused here.
class Sample(object):
x = 100 # class var?
def __init__(self, value):
self.y = value # instance var?
z = 300 # private var? how do we access this outside Sample?
What is the difference between the 3 variable declarations?
Upvotes: 11
Views: 15163
Reputation: 134551
class Sample(object):
x = 100
_a = 1
__b = 11
def __init__(self, value):
self.y = value
self._c = 'private'
self.__d = 'more private'
z = 300
In this example:
x
is class variable, _a
is private class variable (by naming convention),__b
is private class variable (mangled by interpreter), y
is instance variable,_c
is private instance variable (by naming convention),__d
is private instance variable (mangled by interpreter),z
is local variable within scope of __init__
method. In case of single underscore in names, it's strictly a convention. It is still possible to access these variables. In case of double underscore names, they are mangled. It's still possible to circumvent that.
Upvotes: 35
Reputation: 12486
@vartec is spot on. Since you come from Java, however, some clarification is in order:
public
and private
members. Access to private
members is strictly forbidden, and this is enforced by the language.Python only has public members. There is no way to enforce something like java's private
keyword.
If you want to declare that something is an implementation detail only and shouldn't be relied on by other code, you prefix it with a single underscore - _variable
, _function()
. This is a hint to other programmers that they shouldn't use that variable or that function, but it is not enforced.
It might seem like a feature has been omitted from Python, but the culture in Python is "everyone is a consenting adult". If you tell other programmers that something is "private" by prefixing it with an underscore, they will generally take the hint.
Upvotes: 3
Reputation: 59553
You seem to be getting the hang of it. The only one that you were completely wrong about is z = 300
. This is a name that is local to the __init__
method. Python never inserts self
for you in the same manner that C++ and Java will assume this
where it can.
One thing to remember as you continue learning Python is that member functions can always be executed as class members. Consider the following:
>>> class Sample(object):
... def __init__(self, value):
... self.value = value
... def get_value(self):
... return self.value
...
>>> s = Sample(1)
>>> t = Sample(2)
>>> s.get_value()
1
>>> Sample.get_value(s)
1
>>> t.__class__.get_value(s)
1
The last three examples all call the member function of the s
object. The last two use the fact that get_value
is just an attribute of the Sample
class that expects to receive an instance of Sample
as the argument.
Upvotes: 1