Numeric Representation of an Object in Python










-1















I basically want to convert a Python object into a fixed length numeric (not alphanumeric) value. One way, I've come up with is,



import random
x = Car(brand='toyota', model='corolla', price='10000', year=1997)
random.seed(x)

random.random()
0.13436424411240122

random.seed(x)
random.random()
0.13436424411240122


I'm wondering if there is more convenient and generic way (or library) to make this work?










share|improve this question



















  • 1





    Isn't that called a hash? ;)

    – user395760
    Feb 21 '12 at 9:07















-1















I basically want to convert a Python object into a fixed length numeric (not alphanumeric) value. One way, I've come up with is,



import random
x = Car(brand='toyota', model='corolla', price='10000', year=1997)
random.seed(x)

random.random()
0.13436424411240122

random.seed(x)
random.random()
0.13436424411240122


I'm wondering if there is more convenient and generic way (or library) to make this work?










share|improve this question



















  • 1





    Isn't that called a hash? ;)

    – user395760
    Feb 21 '12 at 9:07













-1












-1








-1








I basically want to convert a Python object into a fixed length numeric (not alphanumeric) value. One way, I've come up with is,



import random
x = Car(brand='toyota', model='corolla', price='10000', year=1997)
random.seed(x)

random.random()
0.13436424411240122

random.seed(x)
random.random()
0.13436424411240122


I'm wondering if there is more convenient and generic way (or library) to make this work?










share|improve this question
















I basically want to convert a Python object into a fixed length numeric (not alphanumeric) value. One way, I've come up with is,



import random
x = Car(brand='toyota', model='corolla', price='10000', year=1997)
random.seed(x)

random.random()
0.13436424411240122

random.seed(x)
random.random()
0.13436424411240122


I'm wondering if there is more convenient and generic way (or library) to make this work?







python random






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 20:05







ozgur

















asked Feb 21 '12 at 9:03









ozgurozgur

28k145383




28k145383







  • 1





    Isn't that called a hash? ;)

    – user395760
    Feb 21 '12 at 9:07












  • 1





    Isn't that called a hash? ;)

    – user395760
    Feb 21 '12 at 9:07







1




1





Isn't that called a hash? ;)

– user395760
Feb 21 '12 at 9:07





Isn't that called a hash? ;)

– user395760
Feb 21 '12 at 9:07












5 Answers
5






active

oldest

votes


















1














The way you're now using is:



  • Prone to typo error in your Car object.

  • Fragile if you forget to call random.seed() every time.

  • Case sensitive.

Also, if I were you, I'd like to have a little control on how my number is generated.



The other answers have already showed to you the existence of hashlib.



I would probably use it like this:



class Car:
# ...
def __hash__(self):
md5 = hashlib.md5()
for i in ('brand', 'model', 'price', 'year'):
attr = getattr(self, i)
md5.update(str(attr).lowercase())
return int(md5.hexdigest(), 16)



Reference on the integer conversion: Convert 32-char md5 string to integer.






share|improve this answer
































    1














    def convertObjectIntoFixedLengthNumeric(obj):
    return 17

    x = Car(brand='toyota', model='corolla', price='10000', year=1997)
    convertObjectIntoFixedLengthNumeric(x)
    17


    Very convenient and generic. If not what you were looking for, provide some more information..






    share|improve this answer























    • I say: lol ....

      – Niklas R
      Feb 21 '12 at 9:16











    • nice one. more humor in SO!

      – WeaselFox
      Feb 21 '12 at 9:30






    • 1





      )) as per xkcd.com/221

      – georg
      Feb 21 '12 at 10:01











    • def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

      – Li-aung Yip
      Feb 21 '12 at 10:08



















    0














    You may want to look at the built-in id-function. It returns the memory adress of an object which is always unique, as long as you do not compare the id of an already garbage collected object.






    share|improve this answer






























      0














      Take all the attributes you care about and hash them.



      class Car(...):
      ...
      def __hash__(self):
      return hash((self.brand, self.model, self.price, self.year))

      ...

      print hash(x)





      share|improve this answer






























        0














        Youre talking about a hash function. I think you need to give more info as to what you need this for to get helpful answers.






        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%2f9374699%2fnumeric-representation-of-an-object-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          The way you're now using is:



          • Prone to typo error in your Car object.

          • Fragile if you forget to call random.seed() every time.

          • Case sensitive.

          Also, if I were you, I'd like to have a little control on how my number is generated.



          The other answers have already showed to you the existence of hashlib.



          I would probably use it like this:



          class Car:
          # ...
          def __hash__(self):
          md5 = hashlib.md5()
          for i in ('brand', 'model', 'price', 'year'):
          attr = getattr(self, i)
          md5.update(str(attr).lowercase())
          return int(md5.hexdigest(), 16)



          Reference on the integer conversion: Convert 32-char md5 string to integer.






          share|improve this answer





























            1














            The way you're now using is:



            • Prone to typo error in your Car object.

            • Fragile if you forget to call random.seed() every time.

            • Case sensitive.

            Also, if I were you, I'd like to have a little control on how my number is generated.



            The other answers have already showed to you the existence of hashlib.



            I would probably use it like this:



            class Car:
            # ...
            def __hash__(self):
            md5 = hashlib.md5()
            for i in ('brand', 'model', 'price', 'year'):
            attr = getattr(self, i)
            md5.update(str(attr).lowercase())
            return int(md5.hexdigest(), 16)



            Reference on the integer conversion: Convert 32-char md5 string to integer.






            share|improve this answer



























              1












              1








              1







              The way you're now using is:



              • Prone to typo error in your Car object.

              • Fragile if you forget to call random.seed() every time.

              • Case sensitive.

              Also, if I were you, I'd like to have a little control on how my number is generated.



              The other answers have already showed to you the existence of hashlib.



              I would probably use it like this:



              class Car:
              # ...
              def __hash__(self):
              md5 = hashlib.md5()
              for i in ('brand', 'model', 'price', 'year'):
              attr = getattr(self, i)
              md5.update(str(attr).lowercase())
              return int(md5.hexdigest(), 16)



              Reference on the integer conversion: Convert 32-char md5 string to integer.






              share|improve this answer















              The way you're now using is:



              • Prone to typo error in your Car object.

              • Fragile if you forget to call random.seed() every time.

              • Case sensitive.

              Also, if I were you, I'd like to have a little control on how my number is generated.



              The other answers have already showed to you the existence of hashlib.



              I would probably use it like this:



              class Car:
              # ...
              def __hash__(self):
              md5 = hashlib.md5()
              for i in ('brand', 'model', 'price', 'year'):
              attr = getattr(self, i)
              md5.update(str(attr).lowercase())
              return int(md5.hexdigest(), 16)



              Reference on the integer conversion: Convert 32-char md5 string to integer.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 23 '17 at 12:24









              Community

              11




              11










              answered Feb 21 '12 at 9:16









              Rik PoggiRik Poggi

              19.4k54972




              19.4k54972























                  1














                  def convertObjectIntoFixedLengthNumeric(obj):
                  return 17

                  x = Car(brand='toyota', model='corolla', price='10000', year=1997)
                  convertObjectIntoFixedLengthNumeric(x)
                  17


                  Very convenient and generic. If not what you were looking for, provide some more information..






                  share|improve this answer























                  • I say: lol ....

                    – Niklas R
                    Feb 21 '12 at 9:16











                  • nice one. more humor in SO!

                    – WeaselFox
                    Feb 21 '12 at 9:30






                  • 1





                    )) as per xkcd.com/221

                    – georg
                    Feb 21 '12 at 10:01











                  • def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

                    – Li-aung Yip
                    Feb 21 '12 at 10:08
















                  1














                  def convertObjectIntoFixedLengthNumeric(obj):
                  return 17

                  x = Car(brand='toyota', model='corolla', price='10000', year=1997)
                  convertObjectIntoFixedLengthNumeric(x)
                  17


                  Very convenient and generic. If not what you were looking for, provide some more information..






                  share|improve this answer























                  • I say: lol ....

                    – Niklas R
                    Feb 21 '12 at 9:16











                  • nice one. more humor in SO!

                    – WeaselFox
                    Feb 21 '12 at 9:30






                  • 1





                    )) as per xkcd.com/221

                    – georg
                    Feb 21 '12 at 10:01











                  • def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

                    – Li-aung Yip
                    Feb 21 '12 at 10:08














                  1












                  1








                  1







                  def convertObjectIntoFixedLengthNumeric(obj):
                  return 17

                  x = Car(brand='toyota', model='corolla', price='10000', year=1997)
                  convertObjectIntoFixedLengthNumeric(x)
                  17


                  Very convenient and generic. If not what you were looking for, provide some more information..






                  share|improve this answer













                  def convertObjectIntoFixedLengthNumeric(obj):
                  return 17

                  x = Car(brand='toyota', model='corolla', price='10000', year=1997)
                  convertObjectIntoFixedLengthNumeric(x)
                  17


                  Very convenient and generic. If not what you were looking for, provide some more information..







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 21 '12 at 9:09









                  WesleyWesley

                  1,7091111




                  1,7091111












                  • I say: lol ....

                    – Niklas R
                    Feb 21 '12 at 9:16











                  • nice one. more humor in SO!

                    – WeaselFox
                    Feb 21 '12 at 9:30






                  • 1





                    )) as per xkcd.com/221

                    – georg
                    Feb 21 '12 at 10:01











                  • def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

                    – Li-aung Yip
                    Feb 21 '12 at 10:08


















                  • I say: lol ....

                    – Niklas R
                    Feb 21 '12 at 9:16











                  • nice one. more humor in SO!

                    – WeaselFox
                    Feb 21 '12 at 9:30






                  • 1





                    )) as per xkcd.com/221

                    – georg
                    Feb 21 '12 at 10:01











                  • def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

                    – Li-aung Yip
                    Feb 21 '12 at 10:08

















                  I say: lol ....

                  – Niklas R
                  Feb 21 '12 at 9:16





                  I say: lol ....

                  – Niklas R
                  Feb 21 '12 at 9:16













                  nice one. more humor in SO!

                  – WeaselFox
                  Feb 21 '12 at 9:30





                  nice one. more humor in SO!

                  – WeaselFox
                  Feb 21 '12 at 9:30




                  1




                  1





                  )) as per xkcd.com/221

                  – georg
                  Feb 21 '12 at 10:01





                  )) as per xkcd.com/221

                  – georg
                  Feb 21 '12 at 10:01













                  def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

                  – Li-aung Yip
                  Feb 21 '12 at 10:08






                  def random(): return 6 # number generated by random dice roll, guaranteed to be random. (edit: damn you @thg435)

                  – Li-aung Yip
                  Feb 21 '12 at 10:08












                  0














                  You may want to look at the built-in id-function. It returns the memory adress of an object which is always unique, as long as you do not compare the id of an already garbage collected object.






                  share|improve this answer



























                    0














                    You may want to look at the built-in id-function. It returns the memory adress of an object which is always unique, as long as you do not compare the id of an already garbage collected object.






                    share|improve this answer

























                      0












                      0








                      0







                      You may want to look at the built-in id-function. It returns the memory adress of an object which is always unique, as long as you do not compare the id of an already garbage collected object.






                      share|improve this answer













                      You may want to look at the built-in id-function. It returns the memory adress of an object which is always unique, as long as you do not compare the id of an already garbage collected object.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 21 '12 at 9:10









                      Niklas RNiklas R

                      6,9121662144




                      6,9121662144





















                          0














                          Take all the attributes you care about and hash them.



                          class Car(...):
                          ...
                          def __hash__(self):
                          return hash((self.brand, self.model, self.price, self.year))

                          ...

                          print hash(x)





                          share|improve this answer



























                            0














                            Take all the attributes you care about and hash them.



                            class Car(...):
                            ...
                            def __hash__(self):
                            return hash((self.brand, self.model, self.price, self.year))

                            ...

                            print hash(x)





                            share|improve this answer

























                              0












                              0








                              0







                              Take all the attributes you care about and hash them.



                              class Car(...):
                              ...
                              def __hash__(self):
                              return hash((self.brand, self.model, self.price, self.year))

                              ...

                              print hash(x)





                              share|improve this answer













                              Take all the attributes you care about and hash them.



                              class Car(...):
                              ...
                              def __hash__(self):
                              return hash((self.brand, self.model, self.price, self.year))

                              ...

                              print hash(x)






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Feb 21 '12 at 9:11









                              Ignacio Vazquez-AbramsIgnacio Vazquez-Abrams

                              585k10410671167




                              585k10410671167





















                                  0














                                  Youre talking about a hash function. I think you need to give more info as to what you need this for to get helpful answers.






                                  share|improve this answer



























                                    0














                                    Youre talking about a hash function. I think you need to give more info as to what you need this for to get helpful answers.






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      Youre talking about a hash function. I think you need to give more info as to what you need this for to get helpful answers.






                                      share|improve this answer













                                      Youre talking about a hash function. I think you need to give more info as to what you need this for to get helpful answers.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 21 '12 at 9:12









                                      WeaselFoxWeaselFox

                                      4,63242759




                                      4,63242759



























                                          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%2f9374699%2fnumeric-representation-of-an-object-in-python%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







                                          這個網誌中的熱門文章

                                          How to read a connectionString WITH PROVIDER in .NET Core?

                                          In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                                          Museum of Modern and Contemporary Art of Trento and Rovereto