Messing around with the typical Point class example when learning Python, I noticed that for some reason I can't have a class level (static variable) of the same type as that of the class. E.g.
class Point:
ORIGIN = Point() # doesn't work
def __init__(self, x=0, y=0):
self.x = x
self.y = y
while the same works in Java:
class Point {
private static final Point ORIGIN = new Point(0, 0);
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
The question is: is there any way of achieving the same in Python. Right now I am relying on module level variables and I'm not liking that solution. Also, is there any reason why it can't be done in the body of the class?
There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.
Class variables − Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
You can access all the variables by using the subclass object, and you don't have to create an object of the parent class. This scenario only happens when the class is extended; otherwise, the only way to access it is by using the subclass.
Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.
class Point(object):
pass
Point.ORIGIN = Point()
Assign it after the fact:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
Point.ORIGIN = Point()
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