[英]Does adding public method to subclass violate LSP (Liskov substitution principle)?
If I add public method to subclass and a client program calls added method, client programs can't use parent object instead of subclass. 如果我将子方法添加到子类并且客户端程序调用添加的方法,则客户端程序不能使用父对象而不是子类。
import unittest
class BaseClass(object):
def doSomething(self):
pass
class SubClass(BaseClass):
def doStuff(self):
pass
class Client(object):
def __init__(self, obj):
self.obj = obj
def do(self):
self.obj.doStuff()
class LSPTestCase(unittest.TestCase):
def test_call_subclass_method(self):
client = Client(SubClass())
client.do()
def test_call_baseclass_method(self):
client = Client(BaseClass())
with self.assertRaises(AttributeError):
client.do()
if __name__ == '__main__':
unittest.main()
This case violates LSP? 这种情况违反了LSP?
No as long as all the methods inherrited from the parent class follow the same contract as the parent then LSP is preserved. 否,只要从父类继承的所有方法遵循与父类相同的协定,则保留LSP。
the whole point of LSP is to be able to pass around a subclass as the parent class without any problems. LSP的重点是能够作为父类传递子类而没有任何问题。 It says nothing about not being able to downcast for additional functionality. 它没有说明无法降级其他功能。
Adding a method to a subclass does not violate LSP. 向子类添加方法不会违反LSP。 However, it does violate if you invoke that method by downcasting from a parent class. 但是,如果通过从父类中向下转换来调用该方法, 则会违反该方法。
Robert C. Martin states right in the beginning of his LSP / SOLID paper that: 罗伯特·C·马丁在其LSP / SOLID论文的开头就说 :
select a function based upon the type of an object 根据对象的类型选择一个函数
(...) is an example of a simple violation of the Liskov Substitution Principle. (...)是一个简单违反Liskov替代原则的例子。
Generally, if you end up in situations where you need to downcast or use the instanceof operator, it's better to revisit the use of inheritance in favor of other approaches like composition. 通常,如果您最终遇到需要向下转换或使用instanceof运算符的情况 ,最好重新使用继承来支持其他方法,例如组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.