Python中的继承?
假设我有一个这样的 python
基类:
class BaseClass(object):
def a():
"""This method uses method b(), defined in the inheriting class"""
还有一个类是从 BaseClass
继承而来的:
class UsedByUser(BaseClass):
def b():
"""b() is defined here, yet is used by the base class"""
我的用户只会创建 UsedByUser
类的实例。通常的使用方式是:
if __name__ == '__main__':
# initialize the class used by the user
usedByUser = UsedByUser()
# invoke method a()
usedByUser.a()
我想问的是,上面的用法有没有问题?这样做是否合理,还是说我必须在 BaseClass
中定义方法 b()
,然后在 UsedByUser
中重写它?
4 个回答
听起来你想让 A
调用一个 UsedByUser
的受保护成员函数,而这个函数不能放在抽象的 BaseClass
里。你可以试着在这个受保护的函数前面加一个下划线(虽然这只是 Python 的一种约定,并不是严格要求的,这里有提到)。
class BaseClass(object):
def A(self):
print "Grettings from A"
self._B()
def _B(self):
raise NotImplementedError('b must be implemented by a subclass')
class UsedByUser(BaseClass):
def _B(self):
""" prefix with underscore is a python convention for a protected member function """
print "B rocks!"
if ( __name__=='__main__' ):
usedByUser = UsedByUser()
usedByUser.A()
想了解更多关于这个约定的信息,可以查看 PEP 指南。
编辑:
正如 GaretJax 提到的,我添加了一个 BaseClass
的 _B
方法来让内容更清晰。这个建议真不错!
使用是正确的。类可以定义一些方法,这些方法可以在子类中被重写,但子类也可以定义新的方法。在父类中定义所有子类需要的方法似乎有点没必要。(因为这样的话,
object
也需要定义所有的功能吗?)一个子类的行为通常和另一个子类是不同的。
class Vehicle(object):
def Refuel(self):
# ...class Plane(Vehicle):
def Fly(self):
# ...class Car(Vehicle):
def Drive(self):
# ...
编辑: 我之前看错了代码。
如果仅仅是你创建了它的一个子类,并确保子类有B()
,那么理论上是可以的,但风格不好。给父类定义一些属性和方法,这些是父类自己用到的,这样更有意义也更安全。-> 定义B()
我会在BaseClass
里也定义b
这个方法:
class BaseClass(object):
def b(self):
raise NotImplementedError('b must be implemented by a subclass')
记住:明确的比隐晦的要好,而且既然方法a
反正需要方法b
,那不如抛出一个有意义的异常,而不是一个普通的AttributeError
。
值得注意的是,从语法上讲,这个做法并不是绝对必要的,但它能让代码更清晰,并且强制子类提供一个实现。