从Python中的静态初始化程序访问对象

时间:2014-12-14 02:23:33

标签: java python

以上是我的Static initializer in Python的查询 我试图从它的一个属性中找到一个对象,就像在java中使用静态构造函数一样:

public class TestBuilder {
private String uid;
private String name;
private double speed;
private static ArrayList<TestBuilder> types = new ArrayList<TestBuilder>();
public static final TestBuilder SLEEPY;
public static final TestBuilder SPEEDY;

static {
    SLEEPY = new TestBuilder("1", "slow test", 500.00);
    SPEEDY = new TestBuilder("2", "fast test", 2000.00);
}

private TestBuilder(String uid, String name, double speed){
    this.uid = uid;
    this.name = name;
    this.speed = speed;
    types.add(this);
}

public static TestBuilder getBuilderFromName(String s){
    for (int i = 0; i < types.size(); i++){
        if (((TestBuilder) types.get(i)).name.equals(s)){
            return (TestBuilder) types.get(i);
        }
    }
    return null;
}

在python中我尝试过:

class TestBuilder:
    uid = str()
    name = str()
    speed = float()
    types = []

    def __init__(self, uid, name, speed):
        self.uid = uid
        self.name = name
        self.speed = speed
        self.types.append(self)

    @classmethod
    def lookupType(cls, name):
        for item in cls.types:
            if item.name == name:
                return cls

TestBuilder.SLEEPY = TestBuilder("1","slow test", 500.0)
TestBuilder.SPEEDY = TestBuilder("2","fast test", 2000.0)

然后在测试模块中:

class Tester(unittest.TestCase):
    def test_builder(self):
        dummy = TestBuilder
        ref = dummy.SPEEDY
        objfound = dummy.lookupType("slow test")
        logger.debug("--test_builder() name: "+objfound.name)

虽然在lookupType方法中找到了正确的对象,但在测试中访问时,生成的classfound name属性为空。如何在给定其属性之一的情况下访问正确的TestBuilder对象?

1 个答案:

答案 0 :(得分:3)

您将返回,而不是您找到的实例:

@classmethod
def lookupType(cls, name):
    for item in cls.types:
        if item.name == name:
            return cls
            #      ^^^

改为返回项目:

return item

不使用列表,而是使用字典注册您的类,以便您只需按名称查找它们:

class TestBuilder:
    types = {}

    def __init__(self, uid, name, speed):
        self.uid = uid
        self.name = name
        self.speed = speed
        self.types[name] = self

    @classmethod
    def lookupType(cls, name):
        return cls.types.get(name)

请注意,您的uid = str()speed = float()行只会创建分别设置为空字符串和0.0的类属性。这些行不声明类型,Python不会阻止您的代码在实例级别为这些属性分配不同的对象。