在 Python 中模仿 C# 中的虚函数和纯虚函数的最佳方法是什么?
目前我使用如下模式:
class AbstractClass(object):
'''Abstract class'''
def __init__(self):
assert False, 'Class cannot be instantiated'
def _virtual_init(self):
print 'Base "constructor"'
def pure_virtual_function(self):
assert False, 'Pure virtual function should be derived'
def virtual_function(self):
print 'Base: virtual function'
class Derived1(AbstractClass):
'''All functions derived'''
def __init__(self):
print 'Derived1: constructor'
AbstractClass._virtual_init(self)
def pure_virtual_function(self):
print 'Derived1: pure virtual function'
def virtual_function(self):
print 'Derived1: virtual function'
class Derived2(AbstractClass):
'''Pure virtual method missing.'''
def __init__(self):
print 'Derived2: constructor'
AbstractClass._virtual_init(self)
def virtual_function(self):
print 'Derived3: virtual function'
class Derived3(AbstractClass):
'''Virtual method missing (use base class)'''
def __init__(self):
print 'Derived3: constructor'
AbstractClass._virtual_init(self)
def pure_virtual_function(self):
print 'Derived3: pure virtual function'
# ab = AbstractClass() # Gives error -> OK
print 'DERIVED 1'
dv1 = Derived1()
dv1.pure_virtual_function()
dv1.virtual_function()
print 'DERIVED 2'
dv2 = Derived2()
# dv2.pure_virtual_function() # Gives error: Pure virtual function should be derived -> OK
dv2.virtual_function()
print 'DERIVED 3'
dv3 = Derived3()
# dv3.pure_virtual_function() # Gives error: Pure virtual function should be derived -> OK
dv3.virtual_function()
我得到输出:
DERIVED 1
Derived1: constructor
Base "constructor"
Derived1: pure virtual function
Derived1: virtual function
DERIVED 2
Derived2: constructor
Base "constructor"
Derived3: virtual function
DERIVED 3
Derived3: constructor
Base "constructor"
Derived3: pure virtual function
Base: virtual function
但是我的具体问题是:
- 有没有更优雅的方式在 Python (2.7) 中定义抽象基类?上述解决方案仅在运行时给出错误(例如使用 pylint) Python afaik 中没有“抽象”关键字。
- 有没有更优雅的方式在 Python(2.7)中定义纯虚方法?同样,上述解决方案仅在运行时给出错误。
- 有没有更优雅的方式在 Python (2.7) 中定义虚拟方法?不需要检查,但在 Python afaik 中没有像“virtual”这样的关键字。
提前致谢。