Python中的抽象方法 [英] Abstract methods in Python

查看:20
本文介绍了Python中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Python 继承时遇到问题.虽然这个概念在 Java 中对我来说似乎太容易了,但到目前为止我一直无法在 Python 中理解,这至少让我感到惊讶.

我有一个原型如下:

class Shape():def __init__(self, shape_name):self.shape = shape_name类矩形(形状):def __init__(self, name):self.shape = 名称

在上面的代码中,如何创建一个需要为所有子类实现的抽象方法?

解决方案

沿着这些方向,使用 ABC

导入 abc类形状(对象):__元类__ = abc.ABCMeta@abc.abstractmethoddef method_to_implement(self, input):"""方法文档"""返回

另请阅读此优秀教程:http://www.doughellmann.com/PyMOTW/abc/>

您还可以查看 zope.interface,它在 Python 中引入 ABC 之前使用过.

I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least.

I have a prototype which follow:

class Shape():
   def __init__(self, shape_name):
       self.shape = shape_name

class Rectangle(Shape):
   def __init__(self, name):
       self.shape = name

In the above code how can I make an abstract method that would need to be implemented for all the subclasses?

解决方案

Something along these lines, using ABC

import abc

class Shape(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def method_to_implement(self, input):
        """Method documentation"""
        return

Also read this good tutorial: http://www.doughellmann.com/PyMOTW/abc/

You can also check out zope.interface which was used prior to introduction of ABC in python.

这篇关于Python中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆