[Tutor] class attributes

Alex Kleider alexkleider at gmail.com
Sun Dec 12 19:35:47 EST 2021


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".

Thanks in advance,
Alex


More information about the Tutor mailing list