Problems with properties

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Michael Schneider

    Problems with properties

    Hello All,

    I have been working on learning how to use python properties.

    The get property access is working, but the the set
    property is not working.

    Rather then dispatching the property assignment to setNothing, the
    property object is being replaced with a string.

    I must be doing something very stupid here.

    Could someone please point out my error, I have dents in my forehead
    for this one.

    Thanks,
    Mike



    ------------------------------------------------------------------

    from unittest import TestCase
    import unittest


    class Task:
    def __init__(self,c ommand):
    self._command = command

    def setNothing(self , value):
    raise AttributeError

    def getCommand(self ):
    return self._command

    command=propert y(getCommand, setNothing)


    class taskTest(TestCa se):

    def testTask(self):
    t = Task("dir c:")
    c = t.command
    self.assertEqua ls("dir c:", c)

    # should fail, but doesn't
    t.command = "foo Bar"

    self.assertEqua ls("dir c:", t.command)



    if __name__ == "__main__":
    unittest.main()
  • wittempj@hotmail.com

    #2
    Re: Problems with properties

    If you change it to this it works. You should provide a get and a set
    function for a property.

    class Task:
    def __init__(self, value):
    self._command = value

    def setCommand(self , value):
    self._command = value


    def getCommand(self ):
    return self._command

    command=propert y(getCommand, setCommand)

    class taskTest(TestCa se):
    def testTask(self):
    t = Task("dir c:")
    c = t.command
    self.assertEqua ls("dir c:", c)

    # should fail, but doesn't
    t.command = "foo Bar"
    self.assertEqua ls("dir c:", t.command)


    if __name__ == "__main__":
    unittest.main()

    Comment

    • wittempj@hotmail.com

      #3
      Re: Problems with properties

      If you change it to this it works. You should provide a get and a set
      function for a property.

      class Task:
      def __init__(self, value):
      self._command = value

      def setCommand(self , value):
      self._command = value


      def getCommand(self ):
      return self._command

      command=propert y(getCommand, setCommand)

      class taskTest(TestCa se):
      def testTask(self):
      t = Task("dir c:")
      c = t.command
      self.assertEqua ls("dir c:", c)

      # should fail, but doesn't
      t.command = "foo Bar"
      self.assertEqua ls("dir c:", t.command)


      if __name__ == "__main__":
      unittest.main()

      Comment

      • Benji York

        #4
        Re: Problems with properties

        Michael Schneider wrote:[color=blue]
        > The get property access is working, but the the set
        > property is not working.[/color]

        The classes need to be "new style" for properties to work right. Just
        change "class Task:" to "class Task(object):".

        Your "setNothing " method is unnecessary, if you don't proved a "setter"
        an exception will be raised automatically. Also (if you're using Python
        2.4) you probably want to look at decorator syntax.

        So you're class could look like this:

        class Task(object):
        def __init__(self,c ommand):
        self._command = command

        @property
        def command(self):
        return self._command
        --
        Benji York

        Comment

        • shawn

          #5
          Re: Problems with properties

          I was thinking that in Python2.4, all class definitions inherited from
          new-style classes. There may be a bug here. I can make your code work
          as expected by changing the class definition to:

          class Task(object):


          with that change, the assignment raises an attribute error. You could
          also accomplish the same thing by eliminating the setNothing method and
          defining your property as:

          command=propert y(getCommand)

          or for a really simple case like this, you could even leave off the
          getCommand function and define the property as:

          command=propert y(lambda self: self._command)

          (although I am sure personal tastes vary as to style here).

          Comment

          • Peter Otten

            #6
            Re: Problems with properties

            Michael Schneider wrote:
            [color=blue]
            > Rather then dispatching the property assignment to setNothing, the
            > property object is being replaced with a string.[/color]

            properties are for newstyle classes only (i. e. classes that inherit from
            object).

            from unittest import TestCase
            import unittest

            class Task(object):
            def __init__(self,c ommand):
            self._command = command

            def setNothing(self , value):
            raise AttributeError

            def getCommand(self ):
            return self._command

            command=propert y(getCommand, setNothing)
            # or just
            # command=propert y(getCommand)


            class taskTest(TestCa se):

            def testTask(self):
            t = Task("dir c:")
            c = t.command
            self.assertEqua ls("dir c:", c)

            def set():
            t.command = "foo Bar"
            self.assertRais es(AttributeErr or, set)

            self.assertEqua ls("dir c:", t.command)



            if __name__ == "__main__":
            unittest.main()

            Peter

            Comment

            • Gerrit Holl

              #7
              Re: Problems with properties

              Michael Schneider wrote:[color=blue]
              > Could someone please point out my error, I have dents in my forehead
              > for this one.[/color]
              [color=blue]
              > ------------------------------------------------------------------
              >
              > from unittest import TestCase
              > import unittest[/color]

              Here you need to add:

              __metaclass__ = type

              this will make your classes new-style.

              Gerrit.

              --
              Temperature in Luleå, Norrbotten, Sweden:
              | Current temperature 05-10-14 17:59:48 7.9 degrees Celsius ( 46.3F) |
              --
              Det finns inte dåligt väder, bara dåliga kläder.

              Comment

              • Michael Schneider

                #8
                Re: Problems with properties

                Thanks to all, I added the object as a subclass (should this be
                required for 2.4.1 ???)

                I also switched to the decorator with the @property syntax

                Thank you very much for the help for adding @property to the language.

                what a great language :-)

                Mike


                Michael Schneider wrote:[color=blue]
                > Hello All,
                >
                > I have been working on learning how to use python properties.
                >
                > The get property access is working, but the the set
                > property is not working.
                >
                > Rather then dispatching the property assignment to setNothing, the
                > property object is being replaced with a string.
                >
                > I must be doing something very stupid here.
                >
                > Could someone please point out my error, I have dents in my forehead
                > for this one.
                >
                > Thanks,
                > Mike
                >
                >
                >
                > ------------------------------------------------------------------
                >
                > from unittest import TestCase
                > import unittest
                >
                >
                > class Task:
                > def __init__(self,c ommand):
                > self._command = command
                >
                > def setNothing(self , value):
                > raise AttributeError
                >
                > def getCommand(self ):
                > return self._command
                >
                > command=propert y(getCommand, setNothing)
                >
                >
                > class taskTest(TestCa se):
                >
                > def testTask(self):
                > t = Task("dir c:")
                > c = t.command
                > self.assertEqua ls("dir c:", c)
                >
                > # should fail, but doesn't
                > t.command = "foo Bar"
                >
                > self.assertEqua ls("dir c:", t.command)
                >
                >
                >
                > if __name__ == "__main__":
                > unittest.main()[/color]


                --
                The greatest performance improvement occurs on the transition of from
                the non-working state to the working state.

                Comment

                • Michael Schneider

                  #9
                  Re: Problems with properties

                  Thanks to all, I added the object as a subclass (should this be
                  required for 2.4.1 ???)

                  I also switched to the decorator with the @property syntax

                  Thank you very much for the help for adding @property to the language.

                  what a great language :-)

                  Mike


                  Michael Schneider wrote:[color=blue]
                  > Hello All,
                  >
                  > I have been working on learning how to use python properties.
                  >
                  > The get property access is working, but the the set
                  > property is not working.
                  >
                  > Rather then dispatching the property assignment to setNothing, the
                  > property object is being replaced with a string.
                  >
                  > I must be doing something very stupid here.
                  >
                  > Could someone please point out my error, I have dents in my forehead
                  > for this one.
                  >
                  > Thanks,
                  > Mike
                  >
                  >
                  >
                  > ------------------------------------------------------------------
                  >
                  > from unittest import TestCase
                  > import unittest
                  >
                  >
                  > class Task:
                  > def __init__(self,c ommand):
                  > self._command = command
                  >
                  > def setNothing(self , value):
                  > raise AttributeError
                  >
                  > def getCommand(self ):
                  > return self._command
                  >
                  > command=propert y(getCommand, setNothing)
                  >
                  >
                  > class taskTest(TestCa se):
                  >
                  > def testTask(self):
                  > t = Task("dir c:")
                  > c = t.command
                  > self.assertEqua ls("dir c:", c)
                  >
                  > # should fail, but doesn't
                  > t.command = "foo Bar"
                  >
                  > self.assertEqua ls("dir c:", t.command)
                  >
                  >
                  >
                  > if __name__ == "__main__":
                  > unittest.main()[/color]


                  --
                  The greatest performance improvement occurs on the transition of from
                  the non-working state to the working state.

                  Comment

                  • Alex Martelli

                    #10
                    Re: Problems with properties

                    Michael Schneider <michaelschneid er@fuse.net> wrote:
                    [color=blue]
                    > Thanks to all, I added the object as a subclass (should this be
                    > required for 2.4.1 ???)[/color]

                    It _IS_ required, because Python these days moves *very slowly indeed*
                    before changing semantics of existing code in any way that is not
                    backwards compatible -- we just don't want to break good working code,
                    and there are many millions of lines' worth of such Python code in use
                    around the world. The newstyle object model cannot have identical
                    semantics to the legacy (AKA "classic") one, so it can't become the
                    default without LOTS AND LOTS of years spent with the old-style mode
                    being discouraged and deprecated... but STILL the default.

                    As usual, "should" is a harder question to answer -- one might
                    reasonably say that maintainers of legacy code have had PLENTY of
                    warning time by now, and newstyle OM "should" become the default by,
                    say, 2.6, rather than waiting for 3.0. But, that's not an easy issue to
                    call!


                    Alex

                    Comment

                    • bruno modulix

                      #11
                      Re: Problems with properties

                      wittempj@hotmai l.com wrote:[color=blue]
                      > If you change it to this it works. You should provide a get and a set
                      > function for a property.[/color]

                      The OP did:
                      -> command=propert y(getCommand, setNothing)



                      --
                      bruno desthuilliers
                      python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                      p in 'onurb@xiludom. gro'.split('@')])"

                      Comment

                      Working...