2014-12-07 56 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?