0
class learn:
    def __init__(self, first_name: str, last_name: str, age: int):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def __str__(self, acc):
        if isinstance(acc, learn):
            return f' My name is {self.first_name} {self.last_name} and I am {self.age}'
        raise Exception(f"{acc} is not of class learn ")


acc = learn('Ranjeet', 'Kumar', 22)
print(acc)

TypeError: __str__() missing 1 required positional argument: 'acc'

1
  • 1
    In your own words, where you have def __str__(self, acc):, what do you think the self part means? What do you think it will refer to? Where do you expect the value for acc to come from? Also, did you try to research the problem? For example, you could try putting how do I write a __str__ method in python into a search engine. It really is that easy to look things up. Commented Dec 30, 2021 at 4:09

1 Answer 1

1

As described in the documentation, your custom __str__() method should only declare a single parameter, self that will always be of the type of your class, i.e. learn:

def __str__(self):
    return f' My name is {self.first_name} {self.last_name} and I am {self.age}'

# call via built-in functions str(acc) or print(acc)

Contrast this with a separate function that is detached from the class and could take any number of arguments:

def to_string(obj):
    if isinstance(obj, learn):
        return f' My name is {obj.first_name} {obj.last_name} and I am {obj.age}'
    raise Exception(f"{obj} is not of class learn ")

# call via to_string(acc)

Not the answer you're looking for? Browse other questions tagged or ask your own question.