为了更好地理解这一原理,我尝试将电子商务应用程序的示例代码从Java转换为Python。
下面是包含此示例的Java代码:
public class ProductCatalog {
public void listAllProducts() {
ProductRepository productRepository = ProductFactory.create();
List<String> allProductNames = productRepository.getAllProductNames();
// Display product names
}
}
public interface ProductRepository {
public List<String> getAllProductNames();
}
public SQLProductRepository implements ProductRepository {
public List<String> getAllPRoductNames() {
return Arrays.asList("soap", "toothpaste");
}
}
public class ProductFactory {
public static ProductRepository create() {
return new SQLProductRepository();
}
}
我的python代码是:
import zope.interface
class ProductRespository(zope.interface.Interface):
def getAllProductNames(self) -> list:
pass
@zope.interface.implementer(ProductRespository)
class SQLProductRepository:
def getAllProductNames(self) -> list:
return ["soap", "toothpaste"]
class ProductFactory:
def create(self) -> ProductRespository:
return SQLProductRepository()
class ProductCatalog:
def listAllProducts(self) -> None:
productRespository = ProductRespository()
productRespository = ProductFactory.create()
allProductNames = productRespository.getAllProductNames()
print(allProductNames)
myProductCatalog = ProductCatalog()
myProductCatalog.listAllProducts()
错误为:
Traceback (most recent call last):
File "/Users/me/udemy_courses/solid_principles/5_dependency_invertion.py", line 42, in <module>
myProductCatalog.listAllProducts()
File "/Users/me/udemy_courses/solid_principles/5_dependency_invertion.py", line 35, in listAllProducts
productRespository = ProductFactory.create()
TypeError: ProductFactory.create() missing 1 required positional argument: 'self'
我猜问题可能出在从python创建类或者变量声明上,因为这种语言不需要指定变量的类型。
2条答案
按热度按时间djmepvbi1#
在Java代码中,
ProductFactory.create
被定义为静态方法。如果你想镜像那个设计,你也需要在Python版本中这样做。
bpsygsoo2#
你需要先调用类(对象),然后运行函数,OOP在Python中的工作方式有点不同(我不熟悉Java,但Python是这样做的):
就像上面的例子一样,只要把
productRespository = ProductFactory.create()
替换成productRespository = ProductFactory().create()
就可以了。基本上,你还需要调用这个类来定义self
。