1

I am trying to achieve the following case:

    class ABCD(object):
        def __str__(self): 
            return "some string"

    a=ABCD()
    print a
    some string

Using type:

    A=type("A",(object,),dict(__str__="some string",h=5))
    a=A()
    print a

But get the following error:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'str' object is not callable
1
  • 3
    ... it needs to be a function not a string Commented Jan 12, 2018 at 19:50

1 Answer 1

4

Did you mean to pass a callback? __str__ is to be implemented as an instance method that returns a string.

A = type("A",(object,), dict(__str__=lambda self: "some string" , h=5))
a = A()

print(a)
some string

When you call print on an object, its __str__ method is called. If the object does not have one defined, the the __str__ for the object class is invoked. So, you shouldn't assign a string to __str__ because python'll try to "call" it as a function, throwing a TypeError.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.