根据这个post ,我可以通过访问 str(self.__dict__)
来枚举实例变量,但我不知道如何使用类变量来做到这一点。
这是我要避免的:
# I would like to print out class attributes by overriding `__str__` for that class.
class circle(object):
radius = 3
def __str__(self): # I want to avoid instantiation like this.
return str(circle.radius)
print(circle()) # I want to avoid instantiation. why can't I just print(circle)?
最佳答案
print(circle())
将调用 circle 实例上的 __str__
方法。
class circle:
def __str__(self):
pass
正如您在此处看到的,您通过在父类上使用 def 在 circle 实例上定义了 __str__
。因此,您可以使用 ITS 父级覆盖 CLASS 上的 __str__
方法。
class circle(object):
class __metaclass__(type):
def __str__(cls):
return str(cls.__dict__)
radius = 3
现在,print circle
会给你
{'__module__': '__main__', '__metaclass__': <class '__main__.__metaclass__'>, 'radius': 3, '__dict__': <attribute '__dict__' of 'circle' objects>, '__weakref__': <attribute '__weakref__' of 'circle' objects>, '__doc__': None}
编辑 python3 元类语法
class meta(type):
def __str__(cls):
return str(cls.__dict__)
class circle(object, metaclass=meta):
radius = 3
关于python - 如何在不实例化 Python 中的对象的情况下打印类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49505416/