How to override or perform min/max in python on your own class?










-1















Not sure the best way to title this question, but how can I override or perform min(a, b) or max(a, b) on objects of a class i made? I can override the gt and lt like below but I would like to override the min or max so that I'll be able to use something like max(a, b, c ,d). The class will have multiple property as well, but I think 2 for this example is sufficient.



class MyClass:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2

def __gt__(self, other):
if isinstance(other, MyClass):
if self.item1 > other.item1:
return True
elif self.item1 <= other.item1:
return False
elif self.item2 > other.item2:
return True
elif self.item2 <= other.item2:
return False

def __lt__(self, other):
if isinstance(other, MyClass):
if self.item1 < other.item1:
return True
elif self.item1 >= other.item1:
return False
elif self.item2 < other.item2:
return True
elif self.item2 >= other.item2:
return False


Ex:



a = MyClass(2,3)
b = MyClass(3,3)

print(a > b)
# False


I tried overriding __cmp__ but that doesnt seem to work.



Would like to be able to do max(a, b) and return b object










share|improve this question
























  • You can already call max(a, b, c, ...) with an arbitrary number of arguments, and it'll return whichever is largest, by comparing them to each other. It uses __gt__ and __lt__ to do this, to the best of my knowledge. You can't override max() itself, unfortunately, because it's a built-in method and isn't bound to a specific class (though you could easily write your own method to do the same thing if you wanted). Is there a specific thing you want max() to do here that it doesn't do already, and if so could you give a clearer example?

    – Green Cloak Guy
    Nov 14 '18 at 3:29












  • (1) You are already returning b via max(a, b). max(a, b) is b

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (2) Consider functools.total_ordering

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (3) max(a, b, c ,d) is also already valid. What specifically is wrong with what you've written now?

    – Brad Solomon
    Nov 14 '18 at 3:32







  • 1





    Don't forget the return NotImplemented for when the other object isn't an instance of the expected class.

    – user2357112
    Nov 14 '18 at 5:32















-1















Not sure the best way to title this question, but how can I override or perform min(a, b) or max(a, b) on objects of a class i made? I can override the gt and lt like below but I would like to override the min or max so that I'll be able to use something like max(a, b, c ,d). The class will have multiple property as well, but I think 2 for this example is sufficient.



class MyClass:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2

def __gt__(self, other):
if isinstance(other, MyClass):
if self.item1 > other.item1:
return True
elif self.item1 <= other.item1:
return False
elif self.item2 > other.item2:
return True
elif self.item2 <= other.item2:
return False

def __lt__(self, other):
if isinstance(other, MyClass):
if self.item1 < other.item1:
return True
elif self.item1 >= other.item1:
return False
elif self.item2 < other.item2:
return True
elif self.item2 >= other.item2:
return False


Ex:



a = MyClass(2,3)
b = MyClass(3,3)

print(a > b)
# False


I tried overriding __cmp__ but that doesnt seem to work.



Would like to be able to do max(a, b) and return b object










share|improve this question
























  • You can already call max(a, b, c, ...) with an arbitrary number of arguments, and it'll return whichever is largest, by comparing them to each other. It uses __gt__ and __lt__ to do this, to the best of my knowledge. You can't override max() itself, unfortunately, because it's a built-in method and isn't bound to a specific class (though you could easily write your own method to do the same thing if you wanted). Is there a specific thing you want max() to do here that it doesn't do already, and if so could you give a clearer example?

    – Green Cloak Guy
    Nov 14 '18 at 3:29












  • (1) You are already returning b via max(a, b). max(a, b) is b

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (2) Consider functools.total_ordering

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (3) max(a, b, c ,d) is also already valid. What specifically is wrong with what you've written now?

    – Brad Solomon
    Nov 14 '18 at 3:32







  • 1





    Don't forget the return NotImplemented for when the other object isn't an instance of the expected class.

    – user2357112
    Nov 14 '18 at 5:32













-1












-1








-1








Not sure the best way to title this question, but how can I override or perform min(a, b) or max(a, b) on objects of a class i made? I can override the gt and lt like below but I would like to override the min or max so that I'll be able to use something like max(a, b, c ,d). The class will have multiple property as well, but I think 2 for this example is sufficient.



class MyClass:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2

def __gt__(self, other):
if isinstance(other, MyClass):
if self.item1 > other.item1:
return True
elif self.item1 <= other.item1:
return False
elif self.item2 > other.item2:
return True
elif self.item2 <= other.item2:
return False

def __lt__(self, other):
if isinstance(other, MyClass):
if self.item1 < other.item1:
return True
elif self.item1 >= other.item1:
return False
elif self.item2 < other.item2:
return True
elif self.item2 >= other.item2:
return False


Ex:



a = MyClass(2,3)
b = MyClass(3,3)

print(a > b)
# False


I tried overriding __cmp__ but that doesnt seem to work.



Would like to be able to do max(a, b) and return b object










share|improve this question
















Not sure the best way to title this question, but how can I override or perform min(a, b) or max(a, b) on objects of a class i made? I can override the gt and lt like below but I would like to override the min or max so that I'll be able to use something like max(a, b, c ,d). The class will have multiple property as well, but I think 2 for this example is sufficient.



class MyClass:
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2

def __gt__(self, other):
if isinstance(other, MyClass):
if self.item1 > other.item1:
return True
elif self.item1 <= other.item1:
return False
elif self.item2 > other.item2:
return True
elif self.item2 <= other.item2:
return False

def __lt__(self, other):
if isinstance(other, MyClass):
if self.item1 < other.item1:
return True
elif self.item1 >= other.item1:
return False
elif self.item2 < other.item2:
return True
elif self.item2 >= other.item2:
return False


Ex:



a = MyClass(2,3)
b = MyClass(3,3)

print(a > b)
# False


I tried overriding __cmp__ but that doesnt seem to work.



Would like to be able to do max(a, b) and return b object







python max min






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 3:29









Aqueous Carlos

364314




364314










asked Nov 14 '18 at 3:24









user1179317user1179317

617918




617918












  • You can already call max(a, b, c, ...) with an arbitrary number of arguments, and it'll return whichever is largest, by comparing them to each other. It uses __gt__ and __lt__ to do this, to the best of my knowledge. You can't override max() itself, unfortunately, because it's a built-in method and isn't bound to a specific class (though you could easily write your own method to do the same thing if you wanted). Is there a specific thing you want max() to do here that it doesn't do already, and if so could you give a clearer example?

    – Green Cloak Guy
    Nov 14 '18 at 3:29












  • (1) You are already returning b via max(a, b). max(a, b) is b

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (2) Consider functools.total_ordering

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (3) max(a, b, c ,d) is also already valid. What specifically is wrong with what you've written now?

    – Brad Solomon
    Nov 14 '18 at 3:32







  • 1





    Don't forget the return NotImplemented for when the other object isn't an instance of the expected class.

    – user2357112
    Nov 14 '18 at 5:32

















  • You can already call max(a, b, c, ...) with an arbitrary number of arguments, and it'll return whichever is largest, by comparing them to each other. It uses __gt__ and __lt__ to do this, to the best of my knowledge. You can't override max() itself, unfortunately, because it's a built-in method and isn't bound to a specific class (though you could easily write your own method to do the same thing if you wanted). Is there a specific thing you want max() to do here that it doesn't do already, and if so could you give a clearer example?

    – Green Cloak Guy
    Nov 14 '18 at 3:29












  • (1) You are already returning b via max(a, b). max(a, b) is b

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (2) Consider functools.total_ordering

    – Brad Solomon
    Nov 14 '18 at 3:31











  • (3) max(a, b, c ,d) is also already valid. What specifically is wrong with what you've written now?

    – Brad Solomon
    Nov 14 '18 at 3:32







  • 1





    Don't forget the return NotImplemented for when the other object isn't an instance of the expected class.

    – user2357112
    Nov 14 '18 at 5:32
















You can already call max(a, b, c, ...) with an arbitrary number of arguments, and it'll return whichever is largest, by comparing them to each other. It uses __gt__ and __lt__ to do this, to the best of my knowledge. You can't override max() itself, unfortunately, because it's a built-in method and isn't bound to a specific class (though you could easily write your own method to do the same thing if you wanted). Is there a specific thing you want max() to do here that it doesn't do already, and if so could you give a clearer example?

– Green Cloak Guy
Nov 14 '18 at 3:29






You can already call max(a, b, c, ...) with an arbitrary number of arguments, and it'll return whichever is largest, by comparing them to each other. It uses __gt__ and __lt__ to do this, to the best of my knowledge. You can't override max() itself, unfortunately, because it's a built-in method and isn't bound to a specific class (though you could easily write your own method to do the same thing if you wanted). Is there a specific thing you want max() to do here that it doesn't do already, and if so could you give a clearer example?

– Green Cloak Guy
Nov 14 '18 at 3:29














(1) You are already returning b via max(a, b). max(a, b) is b

– Brad Solomon
Nov 14 '18 at 3:31





(1) You are already returning b via max(a, b). max(a, b) is b

– Brad Solomon
Nov 14 '18 at 3:31













(2) Consider functools.total_ordering

– Brad Solomon
Nov 14 '18 at 3:31





(2) Consider functools.total_ordering

– Brad Solomon
Nov 14 '18 at 3:31













(3) max(a, b, c ,d) is also already valid. What specifically is wrong with what you've written now?

– Brad Solomon
Nov 14 '18 at 3:32






(3) max(a, b, c ,d) is also already valid. What specifically is wrong with what you've written now?

– Brad Solomon
Nov 14 '18 at 3:32





1




1





Don't forget the return NotImplemented for when the other object isn't an instance of the expected class.

– user2357112
Nov 14 '18 at 5:32





Don't forget the return NotImplemented for when the other object isn't an instance of the expected class.

– user2357112
Nov 14 '18 at 5:32












1 Answer
1






active

oldest

votes


















0














Just override the comparison magic methods



class A(object):

def __init__(self, value):
self.value = value

def __lt__(self, other):
return self.value < other.value

def __lt__(self, other):
return self.value <= other.value

def __eq__(self, other):
return self.value == other.value

def __ne__(self, other):
return self.value != other.value

def __gt__(self, other):
return self.value > other.value

def __ge__(self, other):
return self.value < other.value

def __str__(self):
return str(self.value)

a = A(10)
b = A(20)
min(a, b)





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292737%2fhow-to-override-or-perform-min-max-in-python-on-your-own-class%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Just override the comparison magic methods



    class A(object):

    def __init__(self, value):
    self.value = value

    def __lt__(self, other):
    return self.value < other.value

    def __lt__(self, other):
    return self.value <= other.value

    def __eq__(self, other):
    return self.value == other.value

    def __ne__(self, other):
    return self.value != other.value

    def __gt__(self, other):
    return self.value > other.value

    def __ge__(self, other):
    return self.value < other.value

    def __str__(self):
    return str(self.value)

    a = A(10)
    b = A(20)
    min(a, b)





    share|improve this answer





























      0














      Just override the comparison magic methods



      class A(object):

      def __init__(self, value):
      self.value = value

      def __lt__(self, other):
      return self.value < other.value

      def __lt__(self, other):
      return self.value <= other.value

      def __eq__(self, other):
      return self.value == other.value

      def __ne__(self, other):
      return self.value != other.value

      def __gt__(self, other):
      return self.value > other.value

      def __ge__(self, other):
      return self.value < other.value

      def __str__(self):
      return str(self.value)

      a = A(10)
      b = A(20)
      min(a, b)





      share|improve this answer



























        0












        0








        0







        Just override the comparison magic methods



        class A(object):

        def __init__(self, value):
        self.value = value

        def __lt__(self, other):
        return self.value < other.value

        def __lt__(self, other):
        return self.value <= other.value

        def __eq__(self, other):
        return self.value == other.value

        def __ne__(self, other):
        return self.value != other.value

        def __gt__(self, other):
        return self.value > other.value

        def __ge__(self, other):
        return self.value < other.value

        def __str__(self):
        return str(self.value)

        a = A(10)
        b = A(20)
        min(a, b)





        share|improve this answer















        Just override the comparison magic methods



        class A(object):

        def __init__(self, value):
        self.value = value

        def __lt__(self, other):
        return self.value < other.value

        def __lt__(self, other):
        return self.value <= other.value

        def __eq__(self, other):
        return self.value == other.value

        def __ne__(self, other):
        return self.value != other.value

        def __gt__(self, other):
        return self.value > other.value

        def __ge__(self, other):
        return self.value < other.value

        def __str__(self):
        return str(self.value)

        a = A(10)
        b = A(20)
        min(a, b)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 5:31

























        answered Nov 14 '18 at 5:25









        Muruganandhan PeramagounderMuruganandhan Peramagounder

        11




        11





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292737%2fhow-to-override-or-perform-min-max-in-python-on-your-own-class%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo