Reputation: 4122
I have two scripts. The first containing a class, with class variables defined and a function using those class variables. The second script calls the class and function within a function of it's own.
This sort of set up works fine for functions inside a class, however adding class variables is causing me the below error. Can anyone explain why, please and what I need to do to fix?
Thanks
obj1.py:
class my_test_class():
def __init__(self):
self.test1 = 'test1'
self.test2 = 'test2'
self.test3 = 'test3'
def test_func(self, var):
new_var = print(var, self.test1, self.test2, self.test3)
obj2.py
from obj1 import *
def import_test():
target_var = my_test_class.test_func('my test is:')
print(target_var)
import_test()
Error:
Traceback (most recent call last):
File "G:/Python27/Test/obj2.py", line 9, in <module>
import_test()
File "G:/Python27/Test/obj2.py", line 6, in import_test
target_var = my_test_class.test_func('my test is:')
TypeError: test_func() missing 1 required positional argument: 'var'
Upvotes: 0
Views: 389
Reputation: 20490
As the commentors have pointed out, since the test_func
is a class method, we need to call it using a class instance object.
Also print
function returns None, so doing new_var = print(var, self.test1, self.test2, self.test3)
assigns new_var=None
, so if you want to return the variable, you need to assign new_var = ' '.join([var, self.test1, self.test2, self.test3])
, which creates a string with a whitespace between all the words, and return new_var
Combining all of this, the code comes out as follows
class my_test_class():
def __init__(self):
self.test1 = 'test1'
self.test2 = 'test2'
self.test3 = 'test3'
def test_func(self, var):
#Assign value to new_var and return it
new_var = ' '.join([var, self.test1, self.test2, self.test3])
return new_var
def import_test():
#Create instance of my_test_class
test_class = my_test_class()
#Call test_func using instance of my_test_class
print(test_class.test_func('my test is:'))
import_test()
The output will be my test is: test1 test2 test3
Upvotes: 1