[Tutor] class attributes

David bouncingcats at gmail.com
Sun Dec 12 20:23:47 EST 2021


On Mon, 13 Dec 2021 at 11:37, Alex Kleider <alexkleider at gmail.com> wrote:

> I'm trying to write a __repr__ method that can be easily changed to
> show only the attributes in which I'm currently interested and want to
> be able to easily change the attributes of interest.
> My attempted solution is as follows:
>
>     def __repr__(self):
>         attrs = ['SECRETARY',  # an easy to modify listing
>                  'PATTERN',    # of attributes of interest
>                  ]
>         ret = []
>         for attr in attrs:
>             if hasattr(self, attr):
>                 ret.append("{}::{}".format(attr, self.attr))
>             else:
>                 ret.append("{}::unassigned".format(attr))
>         return ','.join(ret)
>
> Not surprisingly, I get the following error:
> """
>     ret.append("{}::{}".format(attr, self.attr))
> AttributeError: 'Club' object has no attribute 'attr'
> """
>
> I'd be grateful if anyone could suggest a way to get around the
> problem. The built in method 'hasattr' is able to do the introspection
> necessary to do its work so it seems what I want should be "doable".

Python has builtin functions getattr() and setattr() which take a
string argument for the attribute name, in the same way such
information is passed to hasattr().


More information about the Tutor mailing list