簡體   English   中英

如何打印類屬性而不在Python中實例化對象?

[英]How to print class attributes without instantiate an object in Python?

根據這篇文章 ,我可以通過訪問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)?

您可以使用類對象本身的__dict__成員(可能過濾掉以__開頭的鍵)。

class circle(object):
    radius = 3

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

print(circle())將在__str__實例上調用__str__方法。

class circle:
  def __str__(self):
    pass

正如您在此處所看到的,您可以通過在父類上使用def來定義__str__實例上的__str__ 因此,您可以使用ITS parent覆蓋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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM