Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static attributes (Python vs Java)

What is the difference between Python class attributes and Java static attributes?

For example,

in Python

class Example:
    attribute = 3

in Java

public class Example {

    private static int attribute;

}

In Python, a static attribute can be accessed using a reference to an instance?

like image 815
Mr. Mars Avatar asked May 03 '16 17:05

Mr. Mars


People also ask

What is a static attribute in Python?

Static means, that the member is on a class level rather on the instance level. Static variables exist only on class level and aren't instantiated. If you change a static variable in one instance of the class, the change will affect its value in all other instances.

Does Python have static variables?

Python does not have a 'static' keyword to declare the static variable. In Python, you simply declare a variable inside the class, note that it should not be inside any method, and that variable will be known as a static or class variable.

How are Python variables different from Java?

The most significant difference between the two is how each uses variables. Python variables are dynamically typed whereas Java variables are statically typed. In Python, type checking is deferred until runtime. There's no need to declare a variable name and type prior to using the variable in an assignment statement.

What are static attributes in Java?

The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.


1 Answers

In Python, you can have a class variable and an instance variable of the same name [Static class variables in Python]:

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3 

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

In Java, you cannot have a static and non-static field with the same name (the following will not compile, you get the error "Duplicate field MyClass.i"):

public class MyClass {
  private static int i;
  private int i;
}

additionally, if you try to assign a static field from an instance, it will change the static field:

public class MyClass {
  private static int i = 3;

  public static void main(String[] args) {
    MyClass m = new MyClass();
    m.i = 4;

    System.out.println(MyClass.i + ", " + m.i);
  }
}

4, 4


In both Java and Python you can access a static variable from an instance, but you don't need to:

Python:

>>> m = MyClass()
>>> m.i
3
>>> MyClass.i
3

Java:

  public static void main(String[] args) {
    System.out.println(new MyClass().i);
    System.out.println(MyClass.i);
  }

3
3

like image 164
Jeffrey Avatar answered Oct 22 '22 23:10

Jeffrey