社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在Python中保护函数不受基类的影响?

KubiK888 • 5 年前 • 1705 次点击  

我现在 learning python中的模板方法模式。

我想知道是否有任何方法可以保护基类中的某些函数,以便子类不能覆盖?如下所示 _primitive_operation_3 从子类重写基类中的相同函数。

import abc

class AbstractClass(metaclass=abc.ABCMeta):
    """
    Define abstract primitive operations that concrete subclasses define
    to implement steps of an algorithm.
    Implement a template method defining the skeleton of an algorithm.
    The template method calls primitive operations as well as operations
    defined in AbstractClass or those of other objects.
    """
    def template_method(self):
        self._primitive_operation_1()
        self._primitive_operation_2()
        self._primitive_operation_3()

    # Functions must be specified by subclass (i.e., subclass variant)
    @abc.abstractmethod
    def _primitive_operation_1(self):
        pass

    # Functions must be specified by subclass (i.e., subclass variant)
    @abc.abstractmethod
    def _primitive_operation_2(self):
        pass

    # Functions inherited and not modified by subclass (i.e., subclass invariant)
    def _primitive_operation_3(self):
        print ('Execute operation #3 from main class')

class ConcreteClass(AbstractClass):
    """
    Implement the primitive operations to carry out
    subclass-specificsteps of the algorithm.
    """
    def _primitive_operation_1(self):
        pass

    def _primitive_operation_2(self):
        pass

    # You can still overwrite it if you want
    def _primitive_operation_3(self):
        print ('Execute operation #3 from subclass')

def main():
    concrete_class = ConcreteClass()
    concrete_class.template_method()

if __name__ == "__main__":
    main()

如果无法防止基类中的方法被重写,我如何放置一些东西来发出自动警报/警告,指示基类中的特定方法已被重写?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52327
 
1705 次点击  
文章 [ 1 ]  |  最新文章 5 年前