Is it correct to use a static method of an abstract class?

Asked

Viewed 86 times

3

During a work assignment I came across the need to use an abstract class method to avoid code duplication. In this case, I came to a question whether it is correct to use a method of a class, which is by definition only a model to be followed.

Ex:

class Animal:
  class Meta:
    abstract = True

  @staticmethod
  def andar():
    print('Andar')


andar = Animal.andar()

Is it correct, from the conceptual point of view, to use the static method of the abstract class? Note: The example is just a way to show what I’m doing.

If this is not good practice, how should I proceed not to hurt the concepts of object orientation?

1 answer

4


The concept depends on the class, so you can only tell with a concrete case. The example just wanted to demonstrate, but precisely because it is artificial it prevents to give a definitive answer. This case seems that it should not do this, but because it even makes sense to have this method as static (might even, I do not know the concrete case, so I am speculating this based on my prior knowledge on the subject).

From the technical point of view everything that can be done is correct, as long as it makes sense at that moment.

If you’re interested in good practice, you fall back into the first paragraph, it’s only good practice if you know the case. What is good for one thing may not be good for another, and if one tries to universalize it ends up making mistakes trying to get it right since one cannot apply the same action to all cases.

If you want to know if it usually gives some problem? Usually not, but can create difficulties.

Some people work with some theories. Some say there shouldn’t even be a static method to start the conversation. I don’t think so. See more in What is the function of a static method?. If you want to strictly follow object orientation, as some preach (I don’t know what the purpose of doing this), or create this type of method.

You need to understand what it’s for to know how to use it well. If it is what you need then it is ok, if it makes sense for the method to exist for the type and not for the object, it must be static.

Have a utility code that serves for another method delegate the execution to it and so avoid duplication of code is perhaps the major reason for a static method.

In some cases you should use a private rather than static method for this, depending on the need. As Python does not have private methods of truth this is done only by convention putting a __ before the name.

What actually makes the method static in Python is not using a parameter self. The decorator allows this method to be called from outside the class using the class name to access, not always want this, may be your case or not.

  • Thank you very much. I understood your point of view and arguments.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.