6

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?

1
  • Python class attributes can be accessed via the class itself or through an instance. Commented May 3, 2016 at 17:38

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.