Hello,
I am a newbie so please forgive any stupidities that I may have done.
I am having a problem creating a list of the instance variables for a class that I created. The following is the source code:
# MyTest.py
class MyTest:
def __init__(self):
self.var1 = 1
self.var2 = 2
self.var3 = 3
def method1(self):
print("in method1")
def method2(self):
print("in method2")
I downloaded this to my STM32F4DISC board that runs MicroPython v1.9.4. The following is my testing session:
MicroPython v1.9.4 on 2018-10-28; F4DISC with STM32F407
Type "help()" for more information.
>>>
>>> import MyTest
>>> dir(MyTest)
['__class__', '__file__', '__name__', 'MyTest']
>>> from MyTest import MyTest
>>> dir(MyTest)
['__class__', '__init__', '__module__', '__name__', '__qualname__', 'method1', 'method2']
>>> t = MyTest()
>>> dir (t)
['__class__', '__dict__', '__init__', '__module__', '__qualname__', 'var1', 'var2', 'var3', 'method1', 'method2']
>>> callable(t.method1)
True
>>> callable(t.var1)
False
>>> v = [i for i in dir(t) if not callable(i)]
>>> v
['__class__', '__dict__', '__init__', '__module__', '__qualname__', 'var1', 'var2', 'var3', 'method1', 'method2']
>>> t.method2()
in method2
>>>
You will notice that "callable(t.method1)" returns "True" and "callable(t.var1) returns False. However,
v = [i for i in dir(t) if not callable(i)]
returns everything, implying that both instance variables and methods are not callable. But we know that method2, at least, is callable because entering "t.method2()" worked.
What is the problem?
Best regards,
Peter
problem creating list of instance variables
Re: problem creating list of instance variables
dir() returns strings, and strings are not callable..
If yu want the actual instance use getattr(t, nameOfAttribute) where nameOfAttribute can be one of the strings returned by dir()
If yu want the actual instance use getattr(t, nameOfAttribute) where nameOfAttribute can be one of the strings returned by dir()
Re: problem creating list of instance variables
Thanks. I'll try it. I'm sure that you are right. Sad to say, I got that line of code from the web at a Python forum, and the poster said that he had tested it.
Best regards,
Peter
Best regards,
Peter