Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

member or class variables in python

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?

like image 640
John Avatar asked Apr 11 '12 13:04

John


People also ask

What is a member variable in Python?

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).

What is a class variable in Python?

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.

What is difference between class variable and instance variable in Python?

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.

What is the difference between a member instance variable and a class variable?

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.


1 Answers

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.

like image 68
vartec Avatar answered Oct 12 '22 05:10

vartec