Static initializer in Python

My question is similar to Is there a static constructor or static initializer in Python?. However I still don't quite follow how to implement a static constructor as I would in Java:

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

In java from another class I could then call TestBuilder.SLEEPY to access a populated class.

In python I have tried:

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)

Then in another module I tried:

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)

However I get a "TypeError: lookupByName() missing 1 required positional argument: 'name'" on the dummy.lookupByName("slow test") call and am not sure why. Does this look like a 'pythonic' way to generate similar functionality to a Java static initializer? Are there alternatives?


The problem is lookupByName is not static and expects an implicit first argument, self . Use the staticmethod decorator in your class definition:

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

This question has more information about static methods: Static methods in Python?

链接地址: http://www.djcxy.com/p/55156.html

上一篇: Python:从字符串名称中调用一个函数

下一篇: Python中的静态初始化器