【问题标题】:How to print one Attribute in a class in Python?如何在 Python 的类中打印一个属性?
【发布时间】:2020-11-11 13:57:01
【问题描述】:

只是我有一个类,该类具有在类示例中打印特定属性的方法:

class Attr:
    def __init__(self, name,
     wattage):
        self.name = name
        self.wattage = wattage
   
    def print_attr(self):
        print("attribute in class is " + getattr(Attr, wattage)

预期的输出是:

attribute name is wattage: test

【问题讨论】:

  • print("attribute in class is " + getattr(self, "wattage"))
  • 很好奇,为什么不直接self.wattage

标签: python python-3.x class attributes class-attributes


【解决方案1】:

您不需要辅助函数,Python 没有访问限制。直接访问属性即可:

a = Attr("Name", 10)

print(a.wattage)

如果你真的想做这样的打印方法,有两种方法:

class Attr:
    def __init__(self, name, wattage):
        self.name = name
        self.wattage = wattage
   
    def print_wattage(self):
        print(f'Wattage in *instance* is {getattr(self, "wattage")}')  # getattr gets by string name

    def print_name(self):
        print(f"Name in *instance* is {self.name}")

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 2021-12-09
    • 2011-08-23
    相关资源
    最近更新 更多