So, I have been trying to implement the following:
from abc import ABC
from abc import abstractmethod
class parent(ABC):
@property
@abstractmethod
def example_variable(self)->str:
...
@abstractmethod
def example_method(self)->int:
...
def __init__(self, foo: int):
self.foo = foo
class child(parent):
def example_method(self)->int:
return self.foo + 10
example_variable = f"This is example variable of value {self.example_method()}"
if __name__ == "__main__":
example_object = child(59)
print(example_object.example_variable)
As you can see, I have created an abstract class with an abstract property and method, and I have tried to implement the child class by using the value of an instance variable to compute a simple value and using that value to set the value of a property using an F string.
But the difficulty is that the interpreter for some reason does not recognise the self reference for the example_method():
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [7], line 17
14 def __init__(self, foo: int):
15 self.foo = foo
---> 17 class child(parent):
18 def example_method(self)->int:
19 return self.foo + 10
Cell In [7], line 21, in child()
18 def example_method(self)->int:
19 return self.foo + 10
---> 21 example_variable = f"This is example variable of value {self.example_method()}"
NameError: name 'self' is not defined
And I have been trying to figure this out, without success.
I tried removing the self reference:
example_variable = f"This is example variable of value {example_method()}"
But then it throws the error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In [10], line 17
14 def __init__(self, foo: int):
15 self.foo = foo
---> 17 class child(parent):
18 def example_variable(self)->int:
19 return self.foo + 10
Cell In [10], line 21, in child()
18 def example_variable(self)->int:
19 return self.foo + 10
---> 21 example_variable = f"This is example variable of value {example_method()}"
NameError: name 'example_method' is not defined
My question is, why doesn't the python interpreter evaluate the self reference correctly? Has the method been not instantiated yet? If so, then what is the correct way to instantiate the example_method()?
selfeven refer to here? You're defining a class attribute withexample_variable = ..., so?? Please clarify what you are trying to achieve.