So this is the class i’m testing:
class Test:
def find_string(self, string):
self.string = string
return string.find(string)
def add_string(self, string):
found = self.find_string('bar')
if found == -1:
string = string + ' bar'
return string
Here is my setup:
test_string = 'foo'
Test1 = Test()
new_string = Test1.add_string(string)
Results
Expected result: foo bar
Result: foo
If I replace the method call in add_string with the direct function find() it works fine. Please help me.
>Solution :
As for me all problem is that variables have similar names and this can be misleading.
Your string.find(string) means "bar".find("bar") but you expect "foo".find("bar")
You would have to use self.string = string in add_string() (instead of find_string()) and later in find_string() use self.string.find(string) instead of string.find(string) – and then you will have "foo" in self.string and "bar" in string so finally self.string.find(string) will mean "foo".find("bar")
class Test:
def find_string(self, string):
return self.string.find(string)
def add_string(self, string):
self.string = string
found = self.find_string('bar')
if found == -1:
string = string + ' bar'
return string
# --- main ---
test_string = 'foo'
test = Test() # PEP8: `lower_case_names` for variables
new_string = test.add_string(test_string)
print(new_string)
PEP 8 — Style Guide for Python Code