-3

simply i have a class that has a method to print a specific attibute in a class example:

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)

the expected output is:

attribute name is wattage: test
Newbieee
  • 167
  • 10

1 Answers1

0

You don't need a helper function for this, Python does not have restricted access. Simply access the attribute directly:

a = Attr("Name", 10)

print(a.wattage)

If you truly want to make a print method like this, there are two ways to do it:

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}")
Sam Morgan
  • 2,445
  • 1
  • 16
  • 25