python抽象基类用法实例分析

WBOY
Release: 2016-06-10 15:10:46
Original
1112 people have browsed it

本文实例讲述了python抽象基类用法。分享给大家供大家参考。具体如下:

定义抽象类,需要使用abc模块,该模块定义了一个元类(ABCMeata),和装饰器 @abstractmethod, @abstractproperty
如果要实例化继承了Foo 的子类,子类必须实现了Foo所有的抽象方法(跟java一样),否则实例化报错。
抽象类不能直接实例化

#!coding=utf-8
from abc import ABCMeta, abstractmethod, abstractproperty
class Foo:
  __metaclass__ = ABCMeta
  @abstractmethod
  #在python3.0中 使用 class Foo(metaclass=ABCMeta)语法
  def spam(self, a, b):
    pass
  @abstractproperty
  def name(self):
    pass
class Bar(Foo):
  def spam(self, a, b):
    print a, b
  def name():
    pass
b = Bar()
b.spam(1,2)
Copy after login

抽象基类支持对已经存在的类进行注册,使其属于该基类,使用register()方法
向抽象基类注册某个类,对于注册类中的实例,涉及后续基类的类检测操作比如(isinstance, issubclass) 将返回True,向抽象基类注册某个类时,不会检查该类是否实现了任何抽象方法或特性,这种注册过程只会影响类型检查

class Crok(object):
  def spam(self, a, c):
    print "gork.span"
Foo.register(Grok)
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!