I want to create some static functions e.g. isEqual
.
However, I can't create a function, that is in scope of class X
, and also refer to X
. <--[1]
MCVE : https://ideone.com/mCjl3l
class X :
str_myField = ""
# parameterized constructor
def __init__(self, str_myField ):
self.str_myField =str_myField
def isEqual(x1 : X,x2: X ): #<==== name 'X' is not defined
return x1.myField == x2.myField
X_a = X();
X_a.str_myField ="a"
X_b = X();
X_b.str_myField ="b"
print(">>"+X.isEqual(X_a,X_b))
I got name 'X' is not defined
error.
Question
Is there such the limitation [1] in python?
(It is true in C++, false in Java, but I am new to Python.)I want to create many static utility functions for
X
.
Is it a bad practice to create a new classX_Util
(instead ofX
) to contain such functions instead?
I don't want to remove the explicit type (i.e. I love x1:X
more than just x
).
Edit
After I got the great link ( How do I type hint a method with the type of the enclosing class? ) suggested by Goion, I have tried to add from __future__ import annotations
at the first line.
The solution is :-
from __future__ import annotations
class X :
str_myField = ""
# parameterized constructor
def __init__(self ):
self.str_myField ="default"
def isEqual(x1 : X,x2: X ):
return x1.str_myField == x2.str_myField
X_a = X();
X_a.str_myField ="a"
X_b = X();
X_b.str_myField ="b"
print(">>"+str(X.isEqual(X_a,X_b)))