python - 如何在不实例化 Python 中的对象的情况下打印类属性?

标签 python class oop

根据这个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/

相关文章:

python - Keras 与 TensorFlow : Use memory as it's needed [ResourceExhaustedError]

ios - 类的 Setter 未被调用

c++ - 类方法的函数对象

.net - 抽象类和接口(interface)之间的主要区别是什么?

python - 使用列表理解将列表列表添加到列表列表

python - 如何在 cygwin 中使用 pip 安装请求?

Python __reverse__ 魔术方法

javascript - JavaScript 中的三维对象

php - 具有不同数量参数的子类构造函数

python - Pandas:计算大写单词的数量