Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class variables of same type as the class

Tags:

python

oop

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?

like image 678
sasuke Avatar asked Dec 06 '10 18:12

sasuke


People also ask

Can a class be a variable type?

There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.

What is a class type variable called?

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.

How do you use a variable of a class in another class?

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.

Are class variables and static variables the same?

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.


2 Answers

class Point(object):
  pass

Point.ORIGIN = Point()
like image 125
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 05:09

Ignacio Vazquez-Abrams


Assign it after the fact:

class Point:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y


Point.ORIGIN = Point()
like image 29
Karl Knechtel Avatar answered Sep 28 '22 05:09

Karl Knechtel