在Python中超越工厂 [英] Moving Beyond Factories in Python

查看:50
本文介绍了在Python中超越工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Java到Python,有人告诉我工厂不是Pythonic的.因此,我正在寻找 a Python方式来执行以下操作.(我过于简化了目标,所以不必描述整个程序,这很复杂.)

Coming to Python from Java, I've been told that factories are not Pythonic. Thus, I'm looking for a the Python way to do something like the following. (I'm oversimplifying my goal so that I don't have to describe my entire program, which is very complicated).

我的脚本将读取人员名称(以及有关人员的一些信息),并由此构造人员类型的对象.名称可以重复,每个名称只需要一个Person实例.这些人也可能属于男人和女人的子类.

My script will read in names of people (along with some information about them) and, from this, construct objects of type Person. The names may be repeated, and I only want one Person instance per name. These People may also belong to subclasses Man and Woman.

执行此操作的一种方法是创建一个PersonFactory,该工厂将返回新实例化的Man或Woman 对先前实例化的具有相同名称的Man/Woman的引用.另一种方法是创建一组所有Person对象,并在实例化新对象之前每次检查是否存在具有给定名称的Person.但是,这两种方法都没有像Pythonic那样令我印象深刻.第一个对于Python来说似乎太麻烦了(创建整个类只是为了处理另一个对象的创建?是吗?),第二个将很快变得昂贵,因为我要处理的名称很多.

One way to do this would be to create a PersonFactory which would either return a newly instantiated Man or Woman or a reference to the previously instantiated Man/Woman with the same name. The other would be to create a set of all Person objects and check each time for the presence of a Person with the given name before instantiating a new object. Neither approach strikes me as Pythonic, though. The first seems a bit too cumbersome for Python (creating a whole class just to handle creation of another object? Really?) and the second will get expensive quickly, as I have a lot of names to process.

推荐答案

我不认为工厂不是Python风格的.但是,您不需要一堂课.Java和Python之间的一大区别是,在Python中,您可以在类之外使用代码.因此,您可能想创建一个工厂函数.或者,您可以使factory成为Person类上的类方法:

I don't think factories are un-Pythonic. You don't need a whole class, though. One big difference between Java and Python is that in Python you can have code outside of classes. So you might want to create a factory function. Or you can make the factory be a class method on the Person class:

class Person:

    name_map = {}

    @classmethod
    def person_from_name(cls, name):
        if name not in cls.name_map:
            cls.name_map[name] = cls(name)
        return cls.name_map[name]

    def __init__(self, name):
        etc...

在Python代码中,通常使用与Java中相同的模式,但是我们并没有做太多的事情.在Java中,您将拥有一个全新的类,这意味着一个全新的.java文件,并且需要将其设置为单例,等等,等等.Java似乎滋生了这种复杂性.一个简单的类方法就可以了,所以就用吧.

Often the same patterns are at work in Python code as in Java, but we don't make as big a deal of it. In Java, you'd have a whole new class, which would imply a whole new .java file, and you'd need to make it a singleton, etc, etc. Java seems to breed this sort of complexity. A simple class method will do, so just use it.

这篇关于在Python中超越工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆