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?
In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).
Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.
Class variables are shared across all objects while instance variables are for data unique to each instance. Instance variable overrides the Class variables having same name which can accidentally introduce bugs or surprising behaviour in our code.
Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With