[Tutor] class attributes

Cameron Simpson cs at cskk.id.au
Sun Dec 12 19:56:10 EST 2021


On 12Dec2021 16:35, 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".

getattr(self, attr_name)

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list