I've been using python for scientific purposes for some years now. I recently became more familiar with class writing, but I feel like I'm missing something regarding the standard way to instantiate classes.
Say I define a class MyClass
.
class MyClass:
def __init__(self):
pass
Then I know that I can map x
to an instance of MyClass
simply with
x = MyClass()
This works well and exactly as I expect.
However, it seems to me that when I use code from standard libraries or from numpy
or scipy
, I don't create objects in the same way: as far as I know, I generally don't use the name of a class to instantiate it. From what I understand, I'd say that this implies that I use neither class methods nor the default constructor of a class, but rather other functions which are defined outside the class.
For example, numpy
's random
module uses a class Generator
to generate random numbers. However, numpy
explicitly recommends not to use the class constructor to get a Generator
instance, and to use instead the default_rng
function from the random
module. So if I want to generate random numbers, I use
rng = numpy.random.default_rng()
to create a Generator
instance. This is done without using explicitly the name of the class.
It seems to me that most of the code that I use is written in the latter way. Why is that so? Is it somehow considered bad practice to directly call default class constructors? Is it considered to be a better practice to have separate functions in a module to create class instances? Is it only because some preprocessing must usually be done before creating an instance of a class? (I guess not, because it that case, why not do that in the initialization of the class?)