I am having difficulties in using python
classes in org-mode
.
Here is a simple illustration of an org mode file:
First let's define a class
#+BEGIN_SRC python :session :exports code
class The_class():
def __init__(self, a):
self.a = a
def add_me(self):
return self.a + self.a
def sqr_me(self):
return self.a**2
#+END_SRC
Then check the class:
#+BEGIN_SRC python :session :exports both :results output
itm = The_class(3)
print('value of itm.a: {0}'.format(itm.a))
print('attributes: {0}'.format(itm.__dict__))
print('methods of itm: {0}'.format(dir(itm)))
#+END_SRC
And make calculation:
#+BEGIN_SRC python :session :exports both :results output
print(itm.add_me())
print(itm.sqr_me())
#+END_SRC
The second block code correctly identifies the attributes, however, it fails
to recognize either self.add_me()
or self.sqr_me()
methods in the dir(self)
.
As a consequence, when upon calling itm.add_me()
, it gives me a:
for example:
#+RESULTS:
: Traceback (most recent call last):
: File "<stdin>", line 1, in <module>
: File "/var/folders/l7/3vzbfyz93z1fz31m3m6srjcm0000gn/T/babel-18019W4Z/python-1801928I", line 1, in <module>
: print(itm.add_me())
: AttributeError: 'The_class' object has no attribute 'add_me' :
Any ideas what is going on?
The problem comes from the newlines. Just remove them.
#+BEGIN_SRC python :session :exports code
class The_class():
def __init__(self, a):
self.a = a
def add_me(self):
return self.a + self.a
def sqr_me(self):
return self.a**2
#+END_SRC