0

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?

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.