gpt4 book ai didi

java - 从Python中的静态初始化器访问对象

转载 作者:行者123 更新时间:2023-12-01 22:32:24 25 4
gpt4 key购买 nike

这是我之前的查询 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 对象?

最佳答案

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

@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() 行只是创 build 置为空字符串和 0.0 的类属性分别。这些行不会声明类型,Python 不会阻止您的代码在实例级别将不同的对象分配给这些属性。

关于java - 从Python中的静态初始化器访问对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com