简体   繁体   English

Python继承,将方法移动到公共类

[英]Python Inheritance, Move method to a common class

I am forgetting OOP terminology which was related to inheritance and which used classes dynamically. 我忘记了与继承有关并且动态使用类的OOP术语。 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. 我的应用程序中有10个模型,每个模型都有此_match_slug方法。 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 . 我想将此方法带到父类,所以当我调用self._match_slug(slug_to_check)它将使用相应的类cls调用该方法。

Thoughts? 思考?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM