0

I recently made a class. Let's say that the class is declared as below.

class MyClass(object):
    def __init__(self, modifiers):
        ....

The problem is, I want to create constant instances of the class:

class MyClass(object):
    def __init__(self, modifiers):
        ....

    CONSTANT_MEMBER_1 = MyClass(my_modifiers)
    CONSTANT_MEMBER_2 = MyClass(my_modifiers)

Unfortunately, Python won't allow me to do so, with error:

E    NameError: global name 'MyClass' is not defined

Any solution for this problem?

One alternative would be creating a 'static' method for the class that will return a same object each time it's called (e.g., MyClass.CONSTANT_MEMBER_1()). But I think I would still prefer to access it using MyClass.CONSTANT_MEMBER_1.

Thanks.

2
  • Can you explain the use case a little more? A "static attribute or method" has a specific meaning here, but you seem to be using "static member" to refer to: "an instance of the class that never changes" Commented Oct 25, 2016 at 15:53
  • @brianpck yes, I meant to refer to "constant instances of the class". Edited. Thanks. Commented Oct 25, 2016 at 16:05

2 Answers 2

2

You can assign to class variables right after the class has been defined.

class MyClass(object):
    def __init__(self, modifiers):
        ....

MyClass.CONSTANT_MEMBER_1 = MyClass(my_modifiers)
MyClass.CONSTANT_MEMBER_2 = MyClass(my_modifiers)
Sign up to request clarification or add additional context in comments.

Comments

-1

Maybe make use of inheritance and custom descriptors, Python Descriptors Demystified

class MyClass(object):
    def __init__(self, color):
        self.color = color
    def __repr__(self):
        return 'I am {}'.format(self.color)

class Foo(MyClass):
    ConstantMember_blue = MyClass('blue')
    ConstantMember_red = MyClass('red')

f = Foo('green')

>>> f
I am green
>>> f.ConstantMember_blue
I am blue
>>> f.ConstantMember_red
I am red
>>> Foo.ConstantMember_blue
I am blue
>>> Foo.ConstantMember_red
I am red
>>>

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.