2

In python there is a method on the type int, namely int.from_bytes. It's not a method on a particular int, instead it's a method on the type. E.g.

>>> int.from_bytes(b'\xee\xff',"big")
61183

>>> int.from_bytes
<built-in method from_bytes of type object at 0x107fdb388>

How do I define something like this? Let's say a class called "point" is defined, how do I define something like

>>> point.from_coordinates(3,5)
<__main__.point object at 0x10c0c9310>

>>> point.from_keys(b'\x12\x3e')
<__main__.point object at 0x10bed5890>

? (Assuming points are initialized by some different method.)

1

2 Answers 2

6

You want classmethod, which is normally used as a decorator:

class point(object):
    @classmethod
    def from_coordinates(cls, x, y):
        pt = cls()
        pt.x, pt.y = x, y
        return pt

This is sometimes called the "alternate constructor" idiom. If there are multiple different ways to construct your type, instead of putting them all into one __init__ method with a mess of optional parameters or varags, put them all into separate classmethods.

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

Comments

3

You can use a classmethod, such as the mocked up example whose init expects ints, but also provides a convenient from_hex that tries to take strings and convert them to integers...

class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    @classmethod
    def from_hex(cls, a, b):
        return cls(int(a, 16), int(b, 16))

The from_hex knows which class it is associated with, so by calling cls(...) you're able to construct a type of MyClass as though you'd written MyClass(a, b) with valid integers yourself.

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.