Home > Blockchain >  Python: Returning a value from a method within a class
Python: Returning a value from a method within a class

Time:05-04

I am new so doing baby steps. Created a simple program of averaging heights.

No error message but return value is: <function Students.total_heights at 0x00000207DC119750>

I didn't need to create 'class.methods' with this script BUT am trying to do this to get the feel of how this works.

Two questions with this.

  1. Material source to read more? Been looking through 'stackoverflow' about my question. I have seen similar questions but the responses are from the perspective of people who have been doing this for years. A lot of heavy terminology. I have been coding for 6 weeks. Working hard and reading a lot.

  2. The script contains a 'main' method that is outside the 'class' structure. Main calls to a method within the class structure. The method within the class works corectly. Great! I now want to 'return' the output of that method so I can use it in the main method.

Thanks.

class Students:

    def __init__(self, list_num):

        self.heights = list_num

    def convert_str_list(self):

        for n in range(0, len(self.heights)):
            self.heights[n] = float(self.heights[n])
            return self.heights
        print(f"Checking: changing str to float {self.heights}")


def main():

    student_heights = input("Input a list of student heights, in cms, with commas inbetween.").split(",")

    print(f"\n\t\tChecking: Student heights straight after removing commas "
          f"and converting to a str list: {student_heights}")

    str_list = Students(student_heights)
    str_list.convert_str_list()

    print(Students.total_heights)

main()

CodePudding user response:

Welcome to coding!

So a couple of things...

  • print(f"Checking: changing str to float {self.heights}") will never run as there is a return statement in the for loop. Anything after a return statement will not run.

I am assuming you want to covert the strings to floats for each height. There are multiple ways to do this.

In your for loop you can use this code

for n in range(0, len(self.heights)):
        self.heights[n] = float(self.heights[n])

This will modify the list that you already created so there is no need to return another list

class Students:

    def __init__(self, list_num):
        # this is a field aka attribute of the Students object
        self.heights = list_num

    # this is a function (method) that belongs to the students object
    # this function will modify the heights list 
    def convert_str_list(self):

        for n in range(0, len(self.heights)):
            self.heights[n] = float(self.heights[n])


def main():

    student_heights = input(
        "Input a list of student heights, in cms, with commas inbetween.").split(",")

    print(f"\n\t\tChecking: Student heights straight after removing commas "
          f"and converting to a str list: {student_heights}")

    # here you are creating (instantiating) a new Student object
    # the list that you created will be assigned to the heights field
    str_list = Students(student_heights)

    # you are calling the convert_str_list() method on the a specific object (instance) namely the str_list student object
    str_list.convert_str_list()
    
    # we want to print the field of the student object
    print(str_list.heights)


main()

here is a good article that describes the OOP paradigm better than I can https://www.programiz.com/python-programming/object-oriented-programming

CodePudding user response:

I assume that you are trying to convert the inputted string into a list ad would like to have it as a function. The current code you are giving doesn't run since the iteration also includes invalid characters like "[", "]", and ",". Here is a solution I guess for your code:

class Students:
    def __init__(self, heights:str):
        self.heights = heights
    def convert_str_list(self):
        total_heights = []
        for n in range(len(self.heights)):
            try:
                total_heights.append(float(self.heights[n]))
            except ValueError:
                continue
        self.heights = total_heights
        print(f"Checking: changing str to float {self.heights}")
        return self.heights


def main():
    student_heights = input("Input a list of student heights, in cms, with commas inbetween.").split(",")
    print(f"\n\t\tChecking: Student heights straight after removing commas "
          f"and converting to a str list: {student_heights}")
    str_list = Students(student_heights)
    str_list.convert_str_list()
    print(str_list.heights)
main()

Make sure to not forget using the same variable you initiated class with to retrieve the variables inside it. You could also use a try catch blocks to process the individual characters from the string or to just use the builtin function eval() to get the list with floats:

student_heights = eval(input("Input a list of student heights, in cms, with commas inbetween."))
  • Related