【问题标题】:How to print class attributes without instantiate an object in Python?如何在不实例化 Python 中的对象的情况下打印类属性?
【发布时间】:2018-03-27 06:04:53
【问题描述】:

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

【问题讨论】:

标签: python class oop


【解决方案1】:

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

【讨论】:

  • 好吧,起初我以为这正是我想要的,但有一个小问题:这段代码似乎只适用于 Python2,而不适用于 Python3。
【解决方案2】:

您可以使用类对象本身的__dict__ 成员(可能过滤掉以__ 开头的键)。

class circle(object):
    radius = 3

print({k: v for k,v in circle.__dict__.items() if not k.startswith('__')}) # prints {'radius': 3}

【讨论】:

  • 您自己尝试过您的代码吗?它正在抛出 SyntaxError。
  • 呃,小错字,来自在电话上写答案。给你。
  • @AleksanderLidtke:确实我已经安装了它,这就是我尝试修复的方式。 :-) 一开始我只是懒得尝试(REPL 中的键盘输入非常糟糕)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
相关资源
最近更新 更多