I'm having the following basic problem in Python. I want to create a constant static instance of a class within the class itself, to be used in methods of the class.
class MyClass(object):
def __init__(self, i : int):
self.i_c = i
newinstance = MyClass(0)
def method(self):
if self == newinstance:
return 'blaba'
else:
return self.i_c
Of course in this example, i could define the instance separately in the module containing my class, but then I could not use it in the methods of the class.
I don't know if it's feasible and I just don't know the right syntax, or if I cannot do this.
Edit: Based on the comments below one workaround is the following
class MyClass(object):
def __init__(self, i : int):
self.i_c = i
MyClass.newinstance = MyClass(0)
def func(thing):
if thing == MyClass.newinstance:
return 'blaba'
else:
return thing.i_c
This works, but func is now not a method of the class MyClass. This is not really problematic in my case, but I guess I can probably define func as a method of MyClass, I just don't really know how.
Ok, I got it, finally thanks to the comments below. This works
class MyClass(object):
def __init__(self, i : int):
self.i_c = i
def method(self):
if self == MyClass.newinstance:
return 'blaba'
else:
return self.i_c
MyClass.newinstance = MyClass(0)