Class Help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ivan Shevanski

    Class Help

    To continue with my previous problems, now I'm trying out classes. But I
    have a problem (which I bet is easily solveable) that I really don't get.
    The numerous tutorials I've looked at just confsed me.For intance:
    [color=blue][color=green][color=darkred]
    >>>class Xyz:[/color][/color][/color]
    .... def y(self):
    .... q = 2
    ....[color=blue][color=green][color=darkred]
    >>>Xyz.y()[/color][/color][/color]
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: unbound method y() must be called with Xyz instance as first
    argument
    (got nothing instead)


    So. . .What do I have to do? I know this is an extremley noob question but I
    think maybe if a person explained it to me I would finally get it =/


    thanks in advance,

    -Ivan

    _______________ _______________ _______________ _______________ _____
    Express yourself instantly with MSN Messenger! Download today - it's FREE!


  • Ron Adam

    #2
    Re: Class Help

    Ivan Shevanski wrote:[color=blue]
    > To continue with my previous problems, now I'm trying out classes. But
    > I have a problem (which I bet is easily solveable) that I really don't
    > get. The numerous tutorials I've looked at just confsed me.For intance:
    >[color=green][color=darkred]
    >>>> class Xyz:[/color][/color]
    >
    > ... def y(self):
    > ... q = 2
    > ...
    >[color=green][color=darkred]
    >>>> Xyz.y()[/color][/color]
    >
    > Traceback (most recent call last):
    > File "<stdin>", line 1, in ?
    > TypeError: unbound method y() must be called with Xyz instance as first
    > argument
    > (got nothing instead)
    >
    >
    > So. . .What do I have to do? I know this is an extremley noob question
    > but I think maybe if a person explained it to me I would finally get it =/
    >
    >
    > thanks in advance,
    >
    > -Ivan[/color]

    Generally you don't use class's directly. Think if them as templates
    for objects. Then you can use that class (template) to create many objects.

    To create an object just call the class and assign the result to a name.

    xyz = Xyz()
    xyz.y()


    Also,

    In your example 'q' is assigned the value 2, but as soon as the method
    'y' exits, it is lost. To keep it around you want to assign it to self.y.

    class Xyz(object): # create an class to create an object instance.
    def y(self)
    self.q = 2

    xyz = Xyz()
    xyz.y()
    print xyz.q # prints 2



    Cheers,
    Ron











    Comment

    • marduk

      #3
      Re: Class Help

      On Sat, 2005-10-01 at 18:58 -0400, Ivan Shevanski wrote:[color=blue]
      > To continue with my previous problems, now I'm trying out classes. But I
      > have a problem (which I bet is easily solveable) that I really don't get.
      > The numerous tutorials I've looked at just confsed me.For intance:
      >[color=green][color=darkred]
      > >>>class Xyz:[/color][/color]
      > ... def y(self):
      > ... q = 2
      > ...[color=green][color=darkred]
      > >>>Xyz.y()[/color][/color]
      > Traceback (most recent call last):
      > File "<stdin>", line 1, in ?
      > TypeError: unbound method y() must be called with Xyz instance as first
      > argument
      > (got nothing instead)
      >
      >
      > So. . .What do I have to do? I know this is an extremley noob question but I
      > think maybe if a person explained it to me I would finally get it =/[/color]


      When you define a class, say Xyz, your are defining your own type. Say
      that Person is a class. And person has a method walk():

      class Person:
      def walk(self):
      ...

      now to use the Person class, you need to create an instance of it. You
      can't just say Person.walk() because Person is a "class"ificatio n, not a
      real object. You need an instance of person.

      jane = Person()

      This creates a new person called "jane". "jane" is an instance of the
      class Person.
      [color=blue][color=green][color=darkred]
      >>> jane[/color][/color][/color]
      <__main__.Perso n instance at 0x2aaaac723710>

      Now we can tell jane to walk:

      jane.walk()

      So what the error is telling you (in a bit confusing way if you're a
      newbie) is that you are calling a method y() but you have not created an
      instance of your Xyz class to do y(). Or, to use my analogy, you are
      telling Person to walk, but you can't make Person walk, you have to
      create a person, jane, and have jane walk.

      Hope this helps, but I recommend you read a good intro to
      object-oriented programming.

      -a

      Comment

      • marduk

        #4
        Re: Class Help

        On Sat, 2005-10-01 at 18:58 -0400, Ivan Shevanski wrote:[color=blue]
        > To continue with my previous problems, now I'm trying out classes. But I
        > have a problem (which I bet is easily solveable) that I really don't get.
        > The numerous tutorials I've looked at just confsed me.For intance:
        >[color=green][color=darkred]
        > >>>class Xyz:[/color][/color]
        > ... def y(self):
        > ... q = 2
        > ...[color=green][color=darkred]
        > >>>Xyz.y()[/color][/color]
        > Traceback (most recent call last):
        > File "<stdin>", line 1, in ?
        > TypeError: unbound method y() must be called with Xyz instance as first
        > argument
        > (got nothing instead)
        >
        >
        > So. . .What do I have to do? I know this is an extremley noob question but I
        > think maybe if a person explained it to me I would finally get it =/[/color]


        When you define a class, say Xyz, your are defining your own type. Say
        that Person is a class. And person has a method walk():

        class Person:
        def walk(self):
        ...

        now to use the Person class, you need to create an instance of it. You
        can't just say Person.walk() because Person is a "class"ificatio n, not a
        real object. You need an instance of person.

        jane = Person()

        This creates a new person called "jane". "jane" is an instance of the
        class Person.
        [color=blue][color=green][color=darkred]
        >>> jane[/color][/color][/color]
        <__main__.Perso n instance at 0x2aaaac723710>

        Now we can tell jane to walk:

        jane.walk()

        So what the error is telling you (in a bit confusing way if you're a
        newbie) is that you are calling a method y() but you have not created an
        instance of your Xyz class to do y(). Or, to use my analogy, you are
        telling Person to walk, but you can't make Person walk, you have to
        create a person, jane, and have jane walk.

        Hope this helps, but I recommend you read a good intro to
        object-oriented programming.

        -a

        Comment

        • Jean-François Doyon

          #5
          Re: Class Help

          You have to crate an instanciation of the class before you can use one.

          So you want to do:

          instance = Xyz()
          instance.y()

          You won't get any output though, might want to do:

          class Xyz:
          def y(self):
          print 'y worked!'

          it's more satisfying :)

          Basically, look into the difference between a class, and the INSTANCE of
          a class.

          Cheers,
          J.F.

          Ivan Shevanski wrote:[color=blue]
          > To continue with my previous problems, now I'm trying out classes. But
          > I have a problem (which I bet is easily solveable) that I really don't
          > get. The numerous tutorials I've looked at just confsed me.For intance:
          >[color=green][color=darkred]
          >>>> class Xyz:[/color][/color]
          >
          > ... def y(self):
          > ... q = 2
          > ...
          >[color=green][color=darkred]
          >>>> Xyz.y()[/color][/color]
          >
          > Traceback (most recent call last):
          > File "<stdin>", line 1, in ?
          > TypeError: unbound method y() must be called with Xyz instance as first
          > argument
          > (got nothing instead)
          >
          >
          > So. . .What do I have to do? I know this is an extremley noob question
          > but I think maybe if a person explained it to me I would finally get it =/
          >
          >
          > thanks in advance,
          >
          > -Ivan
          >
          > _______________ _______________ _______________ _______________ _____
          > Express yourself instantly with MSN Messenger! Download today - it's
          > FREE! http://messenger.msn.click-url.com/g...ave/direct/01/
          >[/color]

          Comment

          • Ron Adam

            #6
            Re: Class Help

            Ron Adam wrote:
            [color=blue]
            > Also,
            >
            > In your example 'q' is assigned the value 2, but as soon as the method
            > 'y' exits, it is lost. To keep it around you want to assign it to self.y.[/color]

            Ooops, That should say ...
            "To keep it around you want to assign it to self.q." <---self.q

            Cheers,
            Ron

            Comment

            • Steven D'Aprano

              #7
              Re: Class Help

              On Sat, 01 Oct 2005 18:58:45 -0400, Ivan Shevanski wrote:
              [color=blue]
              > To continue with my previous problems, now I'm trying out classes. But I
              > have a problem (which I bet is easily solveable) that I really don't get.
              > The numerous tutorials I've looked at just confsed me.For intance:[/color]

              [code snipped]


              You have to keep in mind the difference between a class and an instance of
              a class. To make an analogy with real life, a class is like the idea of
              "dogs in general" and an instance is a specific dog (like Ol' Yella, or
              Rin Tin Tin, or or that little beagle on the Enterprise).

              Normally you create a class, then make one or more instance of the class,
              and work with the instances.

              Some terminology for you to learn: when you create a function inside a
              class, it is called a class method, or just method. Functions and methods
              are not exactly the same, but for now the differences don't concern us.

              So, you create a class with a single method:

              class Klass:
              def spam(self):
              return "spam " * 5

              Notice that the first argument of the method is always "self", even when
              you don't need any arguments.

              Klass is an object, and you can call Klass.spam() if you like, but it will
              fail because you haven't included an argument for self. self must be an
              instance of Klass. So you could do this:

              spam_maker = Klass() # create an instance
              print Klass.spam(spam _maker)

              which will print "spam spam spam " as expected.

              But that's doing extra work. Once you have your instance, you can just
              call the method as if it were a normal function:

              print spam_maker.spam ()

              and it will work the way you expect it to. Behind the scenes, Python
              passes a copy of spam_maker to spam_maker.spam () for you. It can do that
              because spam_maker is an instance.

              A class is a description of how a type of object should work, but you
              normally don't work directly on that high-level description. Normally you
              will work with individual instances, not the class itself. When Timmy
              falls down the well, you tell Rin Tin Tin to go get help, not "dogs in
              the general".

              Python built in objects like lists, strings, ints etc are special types of
              classes built into the language. Here is how we might create a (very
              inefficient!) Python implementation of list:

              class MyList:

              # Class attributes:

              left_delimiter = "["
              right_delimiter = "]"
              item_delimiter = ", "

              # Class methods:

              def __init__(self, *arguments):
              """Create a new instance and fill it with arguments."""
              self.data = arguments # create an instance attribute
              def __str__(self):
              """Convert instance to a string for printing."""
              holder = self.left_delim iter
              for item in self.data:
              holder = holder + str(item) + self.item_delim iter
              holder = holder + self.right_deli miter
              return holder
              def append(self, obj):
              """Append an object to the instance."""
              self.data.appen d(obj)
              # real lists have many more methods...



              Hope this helps.


              --
              Steven.


              Comment

              Working...