-2

I would like to change the output when I call print() on a class (not the instantiation of it!) in Python. I am aware of the __str(self)__ method for instances. I would like to know its "static" equivalent.

class Foo()
    global_var = 2

    # solution code here

print(Foo)

>>> 2

This answer is related but does not answer my question because I have a global variable in my class that should be the print output: How to create a custom string representation for a class object?

EDIT: After a comment I removed the global declaration of the variable and tried to make my problem clearer

deepNdope
  • 179
  • 3
  • 14
  • 1
    That's not a "global class variable". That's just a global variable. It's not part of your class at all. – user2357112 Apr 03 '20 at 21:53
  • Use an actual class variable. – user2357112 Apr 03 '20 at 21:54
  • please don't simply re-post the same question as before. It was closed for a reason – juanpa.arrivillaga Apr 03 '20 at 22:16
  • the reason it was closed for, this post answering my question: https://stackoverflow.com/questions/4932438/how-to-create-a-custom-string-representation-for-a-class-object, did not answer it in my eyes as I don't want to print some specific string but a variable of my class. There was a prompt to open a new question in this case which I did. I also tried to make the question clearer than in the previous post – deepNdope Apr 04 '20 at 14:46

2 Answers2

0
  print(Foo.this_is_what_i_need())

Or better yet skip function in your class

    print(Foo.global_var)
Pmac1687
  • 9
  • 1
0

The link you provided (almost) has a solution:

from six import with_metaclass

class _Foo(type):
    global_var = 2
    def __repr__(self):
        return "The global_var is " + str(self.global_var)

class Foo(with_metaclass(_Foo)):
    pass

print(Foo)
# Prints: The global_var is 2
RafazZ
  • 4,049
  • 2
  • 20
  • 39