2014-12-07 55 views
0

我的问题与Is there a static constructor or static initializer in Python?类似。但是我还是不太明白如何实现静态构造函数,我会在Java中:Python中的静态初始化器

public class TestBuilder { 
    private String uid; 
    private String name; 
    private double speed; 

    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; 
    } 

    public double getSpeed(){ 
     return speed; 
    } 

    public String getUid() { 
     return uid; 
    } 

    public String getName() { 
     return name; 
    } 

在java中从另一个类,那么我可以打电话给TestBuilder.SLEEPY访问填充类。

在Python中我曾尝试:

class TestBuilder: 
    uid = str() 
    name = str() 
    speed = float() 

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

    def lookupByName(self, name): 
     result = None 
     members = [attr for attr in dir(TestBuilder()) if not callable(attr) and not attr.startswith("__")] 
     for testbuilder in members: 
     if testbuilder.name == name: 
      result = testbuilder.uid 
      break   
     return result 

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

然后在另一个模块我想:

from examples.testbuilder import TestBuilder 
import unittest 

class Tester(unittest.TestCase): 

    def test_builder(self): 
     dummy = TestBuilder 
     ref = dummy.SPEEDY 
     sleepyid = dummy.lookupByName("slow test") 
     self.assertTrue(dummy.SPEEDY.__str__() == ref.__str__()) 
     self.assertEqual(1, sleepyid) 

不过,我得到一个“类型错误:lookupByName()失踪1个人需要的位置参数: '名' “在dummy.lookupByName(”慢速测试“)调用,我不知道为什么。 这看起来像是一种“pythonic”方法来生成与Java静态初始化程序类似的功能吗?有替代品吗?

回答

3

问题是lookupByName不是静态的,需要一个隐含的第一个参数self。使用类定义中的staticmethod装饰:

class TestBuilder: 
    ... 
    @staticmethod 
    def lookupByName(name): 
     result = None 
     ... 

这个问题有关于静态方法的详细信息:Static methods in Python?