Kashif Siddiqui
Kashif Siddiqui

Reputation: 1546

How to return instance of a class from its static attribute in python

Just curious, Is it possible to keep static attrs in a class that returns instantiated objects for the same class? Specifically not using a factory method but attr

class Money:
    CENT = Money('cent')

    def __init__(self, value):
        self.value = value

Money.CENT    #==> Returns Money('cent')

The best I could come up with is, But not within the same class.

class SampleMoney:
    CENT = Money('cent')
    DOLLAR = Something('dollar')

SampleMoney.CENT #==> Money('cent')

Upvotes: 0

Views: 66

Answers (1)

Eric
Eric

Reputation: 97571

You could use the following hack to create a class property:

class Something:
    class __metaclass__:
        @property
        def EMPTY(cls):
            return cls('empty')

Alternatively, just define it after?

class Something:
    # ...

Something.EMPTY = Something('empty')

Upvotes: 1

Related Questions