Weirdness comparing strings

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mr.SpOOn

    Weirdness comparing strings

    Hi,
    I have this piece of code:

    class Note():
    ...
    ...
    def has_the_same_na me(self, note):
    return self == note

    def __str__(self):
    return self.note_name + accidentals[self.accidental s]

    __repr__ = __str__

    if __name__ == '__main__':
    n = Note('B')
    n2 = Note('B')
    print n
    print n2
    print n.has_the_same_ name(n2)

    I'd expect to get "True", because their string representation is
    actually the same, instead the output is:

    B
    B
    False

    I think I'm missing something stupid. Where am I wrong?
  • Scott David Daniels

    #2
    Re: Weirdness comparing strings

    Mr.SpOOn wrote:
    Hi,
    I have this piece of code:
    >
    class Note():
    Unless you _need_ old-style, use new style.
    ...
    def has_the_same_na me(self, note):
    return self == note
    Define equality (__eq__) if you want to compare for equality.
    def __str__(self):
    return self.note_name + accidentals[self.accidental s]
    >
    __repr__ = __str__
    If str and repr are to be equal, just define repr.


    class Note(object):
    def __init__(self, note, accidentals):
    self.note_name = note
    self.accidental s = accidentals

    def has_the_same_na me(self, note):
    return self == note

    def __eq__(self, other):
    return isinstance(othe r, Note) and (
    self.note_name == other.note_name and
    self.accidental s == other.accidenta ls)

    def __repr__(self):
    return self.note_name + accidentals[self.accidental s]


    --Scott David Daniels
    Scott.Daniels@A cm.Org

    Comment

    Working...