Reputation: 115
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.
Upvotes: 0
Views: 891
Reputation: 23753
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
>>>
Upvotes: -1
Reputation: 59112
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)
Upvotes: 2