简单地说,我有一个类,它有一个打印类示例中特定属性的方法:
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
您不需要助手函数,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}")