P
P
PyCi2021-12-03 12:43:18
Python
PyCi, 2021-12-03 12:43:18

How to make one function for all classes?

I have many classes that use the same function, but with a slight difference. How can I put it in a separate class so as not to repeat myself?

class AttrNameSerializer(serializers.ModelSerializer):

    class Meta:
        model = AttributeName
        fields = '__all__'

    def to_representation(self, instance):
        result = super(AttrNameSerializer, self).to_representation(
            instance)
        return OrderedDict([(key, result[key]) for key in result if
                            result[key] is not None])

class ProductSerializer(serializers.ModelSerializer):
    published_on = serializers.DateTimeField(format='iso-8601')

    class Meta:
        model = Product
        fields = '__all__'

    def to_representation(self, instance):
        result = super(ProductSerializer, self).to_representation(
            instance)
        return OrderedDict([(key, result[key]) for key in result if
                            result[key] is not None])

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-12-03
@PyCi

Obviously move it to a base class or mixin.

R
rPman, 2021-12-03
@rPman

I will not talk about a specific example now, but in general

the same function, but with a slight difference

universal solution - metaprogramming
This is often considered shit coding, other languages ​​like c++ or c# have a preprocessor, a simple template language that ignores partially or completely the syntactic features of the base language
. The code of the function is divided into parts that are similar in different instances of these functions, and differences are introduced through function parameters preprocessor.
In this case, the differences are in the class name, in the proxy call to super and the string defining published_on, respectively, everything else in the function can be defined in the preprocessor macro and generate the code the required number of times by calling this macro.
Personally, when I need to do metaprogramming, (I use don’t laugh php) by adding a call to my utility to the assembly, but nothing prevents me from taking it ready, the first google gives filepp or gpp (crash macro syntax)
approach disadvantages - source files before macro may not be supported IDEs and editors, broken syntax control and confusing error messages can be a turn off

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question