1

I am forgetting OOP terminology which was related to inheritance and which used classes dynamically. Here is what I am looking for.

    @classmethod
    def _match_slug(cls, slug):
        """ Method that checks if we still have a match in the db for current 'slug' """
        return cls.objects.filter(slug=slug).count()

I have 10 models in my application and each has this _match_slug method. I want to take this method to the parent class, so when I call self._match_slug(slug_to_check) it calls the method with its appropriate class cls.

Thoughts?

4
  • I think what you are referring to is Polymorphism. I thinkt the method should work as is if it is defined int he parent class. Are you getting any errors when attempting to use it? Commented Jul 31, 2015 at 16:53
  • You probably want to make a Mixin and use it as base class for you 10 models. Commented Jul 31, 2015 at 16:59
  • I havn't tried it, and I was confused about what it was and how to use that, I had a concept in my mind. Can somone write a demo code for python? Commented Jul 31, 2015 at 17:16
  • 2
    You already have it! Move that method to a class, and make sure all of your models extend it, like this class MyModel(Parent): Commented Jul 31, 2015 at 17:17

1 Answer 1

1

Move the method to your parent class:

class Parent(object):

    @classmethod
    def _match_slug(cls, slug):
        """ Method that checks if we still have a match in the db for current 'slug' """
        return cls.objects.filter(slug=slug).count()

class Child(Parent):
    ...

c = Child()
# Equivalent to Parent._match_slug(c.__class__, x)
c._match_slug(x)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.