Comparing objects in a conditional, Python 3 -
i have following code in program used append setting list or if in list remove it. if setting has value should sent self.commit_setting , if not self.commit_setting passed. wise removing setting except instead of committing setting undoes it.
no_color = gdk.rgba(red=0.000000, green=0.000000, blue=0.000000, alpha=1.000000) if setting in self.setting_lst: self.setting_lst.remove(setting) # if setting in list remove # note: get_rgba() returns gdk.rgba object if self.get_rgba() == no_color: # if value not set pass pass else: self.undo_setting() else: self.setting_lst.append(setting) # add setting list if not in if self.get_rgba() == no_color: # if value not set pass pass else: self.commit_setting()
currently code working fine me simplify using if out else, implying if condition not met else. put:
if self.get_rgba() != no_color: self.commit_setting()
unfortunately when self.commit_setting() or undo_setting() executed if color equal no_color. why this? "!" operator not work comparing objects?
assuming , self.get_rgba()
, no_color
return objects (instances) of same class . can have class overwrite __eq__
function internally called when checking equality , __ne__
not equality -
def __eq__(self, other): return self.somethings = other.somethings def __ne__(self, other): return not self.__eq__(other)
you can define 1 of these (you not need define both).
edit:
also , before python 3.0 , can also __cmp__
function in similar way, should return -1 if self
has less value , 1 if self
has greater value , 0 if self
equal other
.
the above functions - __eq__
or __ne__
called rich comparison operators , complete list can check out - rich comparison operators
Comments
Post a Comment