Static Attributes (Python vs Java)

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

For instance,

in python

class Example: attribute = 3 

in java

 public class Example { private static int attribute; } 

In Python, can I access a static attribute using an instance reference?

+5
source share
1 answer

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

 >>> class MyClass: ... i = 3 ... >>> MyClass.i 3 >>> m = MyClass() >>> mi = 4 >>> MyClass.i, mi >>> (3, 4) 

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

 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(); mi = 4; System.out.println(MyClass.i + ", " + mi); } } 

4, 4


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

Python:

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

Java:

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

3
3

+4
source

All Articles