What you are describing is certainly possible, but it is unusual:
- in many object-oriented languages, like Java, classes are not first-rate values and cannot be used like this at all;
- even in languages like Python where classes are first-rate values and can be used like this, most people still use an instance.
(By the way, some of my comments below are not aimed at you directly, but other readers who may not be familiar with the concepts you refer to, such as singletons.)
In the OOP (object-oriented programming) world, the most common solution to your problem is called a singleton. People are divided over whether singletons are great, or an anti-pattern.
(Personally, I think that singletons like None are great, but most other uses are problematic.)
An alternative to the Singleton design (anti-)pattern is the Borg.
A lesser known alternative is to just use the class itself as the one and only value, but as you point out, it has disadvantages:
- you have to make all the methods
classmethod
;
-
property
will not work;
- this design is so rare that it doesn’t have a catchy name, or even a boring name;
- will likely confuse linters and automated code checkers;
- many programmers are like cats, and hate and fear anything different, and this is certainly different!
I don’t understand your argument that you can’t use isinstance
. You can, but your class-that-is-like-a-singleton will only compare as an instance of type
.
The benefits are minor:
- avoid the need to write Singleton boilerplate;
- save a tiny amount of memory by avoiding creating an instance.
There is another solution: just use a module.
A module contains state (global variables) and behaviour (functions), just like a class. Like a singleton, you can only have one instance of a module at any one time time: the interpreter enforces that rule for you automatically. As an example of that, see the random
module.
So that’s four solutions to the problem of having only one instance with state and behaviour:
- use a Singleton;
- forget about one instance, use Borg with many instances with shared state;
- use the class object directly;
- use a module.
Which is better is a question of what exactly you are doing, who else is reading your code, and also a matter of taste.