简体   繁体   中英

How do I write a class function that returns a value as soon as the class is called?

I have to complete the following challenge:

The object created from a class C contains an array of integers, passed in when the object is created. Define a text representation of an object that returns an expression that sums up all the numbers in an array, in the order as in the array.

Example:

 C([5,12]) -> "5+12=17" C([6,0,15]) -> "6+0+15=21"

I tried to return do this in the __init__() function but it cannot return a value.

class C():
    def __init__(self, array):
        self.array = array

        # ctreating the text
        sum = 0
        text = ""
        for i in range(len(array)):
            sum += array[i]
            text += str(array[i])
            if i < len(array):
                text += "+"
        text += f"={sum}"

        # trying to return the ready text
        return(text)

C([5, 12])

It kind of works if I print() it intead of return but I'm supposed to return the value.

You are very close, you just need to separate initialization in __init__ and computations in another function:

class C():

    def __init__(self, array):
        self.array = array

    def print_sum(self):
        # creating the text
        sum = 0
        text = ""
        for i in range(len(self.array)):
            sum += array[i]
            text += str(self.array[i])
            if i < len(self.array):
                text += "+"
        text += f"={sum}"

        # trying to return the ready text
        return(text)
        

print(C([5, 12]).print_sum())

Another possibility as @John Gordon mentioned is:

class C():

    def __init__(self, array):
        self.array = array

    def __str__(self):
        # creating the text
        sum = 0
        text = ""
        for i in range(len(self.array)):
            sum += array[i]
            text += str(self.array[i])
            if i < len(self.array):
                text += "+"
        text += f"={sum}"

        # trying to return the ready text
        return(text)
        

print(C([5, 12]))

Now just printing the class will automatically print the string representation of the sum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM