Python中的静态初始化器

我的问题类似于Python中是否存在静态构造函数或静态初始化器? 不过,我仍然不太了解如何像在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;
    }

在另一个类的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)

然而,我得到一个“TypeError:lookupByName()在dummy.lookupByName(”慢测试“)调用中缺少1所需的位置参数:'name'”,我不知道为什么。 这看起来像是一种“pythonic”方式来生成与Java静态初始化程序类似的功能吗? 有替代品吗?


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

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

这个问题有更多关于静态方法的信息:Python中的静态方法?

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

上一篇: Static initializer in Python

下一篇: Deciding to use @staticmethod, @property, or manager in Django