Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static classes in Python

I once read (I think on a page from Microsoft) that it's a good way to use static classes, when you don't NEED two or more instances of a class.

I'm writing a program in Python. Is it a bad style, if I use @classmethod for every method of a class?

like image 906
rynd Avatar asked Apr 30 '12 17:04

rynd


People also ask

What are static classes?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

What is a static method in Python?

What is a static method? Static methods, much like class methods, are methods that are bound to a class rather than its object. They do not require a class instance creation. So, they are not dependent on the state of the object.

What are static classes used for?

Static classes are used as containers for static members. Static methods and static properties are the most-used members of a static class. All static members are called directly using the class name. Static methods do a specific job and are called directly using a type name, rather than the instance of a type.


2 Answers

Generally, usage like this is better done by just using functions in a module, without a class at all.

like image 135
Gareth Latty Avatar answered Sep 21 '22 04:09

Gareth Latty


It's terrible style, unless you actually need to access the class.

A static method [...] does not translate to a Python classmethod. Oh sure, it results in more or less the same effect, but the goal of a classmethod is actually to do something that's usually not even possible [...] (like inheriting a non-default constructor). The idiomatic translation of a [...] static method is usually a module-level function, not a classmethod or staticmethod.

source

like image 41
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 04:09

Ignacio Vazquez-Abrams