0

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')
8
  • Does it need to be an attr or can it be a method? Commented Mar 17, 2017 at 3:10
  • 1
    Why would you want to do that, I am sure there is a better way to serve your use case. Commented Mar 17, 2017 at 3:11
  • attr, With method it is easy to return a new instance Commented Mar 17, 2017 at 3:12
  • Yes, that's what I was thinking. Using a method is the factory pattern Commented Mar 17, 2017 at 3:12
  • 1
    Just put Something.EMPTY = Something('empty') after the class definiton. Commented Mar 17, 2017 at 3:15

1 Answer 1

1

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')
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.