0

I have a class (named MyClass) with a function (named MyFunct).

when I print it, it's ok but when I use .format I have some issues:

class MyClass:
    var = 2
    def MyFunct(numb):
        return numb + 1

print(MyClass.var)
>>> 2
print(MyClass.MyFunct(5))
>>> 6

print("{.var}".format(MyClass))
>>> 2

print("{.MyFunct(5)}".format(MyClass))
>>> AttributeError: type object 'MyClass' has no attribute 'MyFunct(5)'

I need to use .format for some reason, and I would like to add posibility to add function :/

Thanks for you'r help <3 !

VOLTIS
  • 27
  • 6
  • Maybe use `f` strings instead? `print(f"{MyClass.MyFunct(5)}")` – vmemmap Aug 17 '20 at 14:05
  • @TinNguyen It works for me. `print(f"{MyClass.MyFunct(5)}")`. And of course you can execute functions inside strings – vmemmap Aug 17 '20 at 14:07
  • what's wrong with just `"{}".format(MyClass.MyFunct(5))`? – M Z Aug 17 '20 at 14:08
  • @r0ei you are correct, just tried it out. – Tin Nguyen Aug 17 '20 at 14:09
  • Unrelated to your question, but it is a good idea to put the [`@staticmethod`](https://docs.python.org/3/library/functions.html#staticmethod) decorator on functions like this. Without that decorator, when someone calls it on an instance of the class it will pass the class instance as the parameter (i.e. `MyClass().MyFunct()` is equivalent to `MyClass.MyFunct(MyClass())`), which doesn't appear to be what you want. – Arthur Tacca Aug 17 '20 at 14:34

2 Answers2

0

string.Formatter class in python can only parse arguments, he cannot execute anything https://docs.python.org/3.4/library/string.html#string.Formatter.vformat

print("{.+4}".format(1))

AttributeError: 'int' object has no attribute '+4'

1.+4

5

If you want to execute something use format string:

print(f"{MyClass.MyFunct(5)}")
ooolllooo
  • 353
  • 1
  • 3
  • 11
0

When you write the expression:

MyClass.MyFunct(5)

Note that two things happen in a very specific order. To help illustrate that I will write it out as two separate lines of code:

f = MyClass.MyFunct
f(5)

This is equivalent to the single line mentioned at the start. Note that MyClass.MyFunct is evaluated first, getting the attribute named "MyFunct" from MyClass and returning a function object. Only then is the function object called, in this case with the parameter 5.

You can see from this that you are not getting an attribute of MyClass called "MyFunct(5)". There is no such attribute, only "var" and "MyClass". But that's what you're asking format to do - all it can do is get attributes, not execute methods, as others have said.

Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49