Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Class – Can't find out how to use method return value within another method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading