I will get straight to the point. I have been trying to find different ways in which I can check if an instance attribute exists in a method of a class which has not been called from the instance of the class.
Consider the following example:
class Main:
def thing1(self):
self.x = 10
m = Main()
print(m.x)
This code above will not work, until I call the method, e.g:
class Main:
def thing1(self):
self.x = 10
m = Main()
m.thing1()
print(m.x)
or
class Main:
def __init__(self):
self.thing1()
def thing1(self):
self.x = 10
m = Main()
print(m.x)
I want to know if there is a way I can check if this instance attribute exists in the method without having to call it.
I have tried using:
- hasattr()
- dir()
- __ dict __
None of them will show that I have a instance attribute called 'x' in thing1
As well as this, I would greatly appreciate it if you could show me how I could check if an instance attribute in a method exists through another method.
class Main:
def thing1(self):
self.x = 10
def check(self):
# Is there a way I can check if 'x' exists in the method names thing1, without having to call it.
m = Main()
Thank you for taking the time to read this question, and I hope that you have a great day!