I am new. Can you help me with classes?

I am very new to Python programming. I am currently studying from a book "Learning Python" by O'Reilly. I was doing fairly well, but I got stuck in Chapter 6: Classes. The problem I was stuck on was this.

class FirstClass:
def setdata(self, value):
self.data = value
def display(self):
print self.data

These are the examples the book used with that class:

>>>x = FirstClass()
>>>x.setdata("King Arthur")
>>>x.display()
>>>King Arthur

That's the part I don't get. In function setdata, there are two arguments. One is "self" and other is "value". But, in the example, the book only used one, "King Arthur". Also, "self" was never defined. Shouldn't it display an error like "NameError: name 'self' is not defined"? Someone please help!

Comments

  • [b][red]This message was edited by Moderator at 2003-8-28 11:51:39[/red][/b][hr]
    : I am very new to Python programming. I am currently studying from a book "Learning Python" by O'Reilly. I was doing fairly well, but I got stuck in Chapter 6: Classes. The problem I was stuck on was this.
    : [code]
    : class FirstClass:
    : def setdata(self, value):
    : self.data = value
    : def display(self):
    : print self.data
    : [/code]
    : These are the examples the book used with that class:
    :
    : >>>x = FirstClass()
    : >>>x.setdata("King Arthur")
    : >>>x.display()
    : >>>King Arthur
    :
    : That's the part I don't get. In function setdata, there are two arguments. One is "self" and other is "value". But, in the example, the book only used one, "King Arthur". Also, "self" was never defined. Shouldn't it display an error like "NameError: name 'self' is not defined"? Someone please help!

    Are you familiar with Java or C++? In those languages, every class has an implicit pointer to an instance of itself named "this". In Python, class methods are defined with an explicit reference to an instance of that class. By convention people mostly use "self", though can call it anything you want. When you actually call a method on an object, Python automatically binds that variable to the object calling the method. Each object only has a pointer back to the method defined in the class, not a copy of the method in itself. All objects therefore call the same function, so for the function to know which object it's operating on, it needs a reference to that object, which is automatically the first argument the function accepts.

    Does that help?

    Basically, when you say:

    x.setdata("King Arthur")

    Python is calling:

    FirstClass.setdata(x, "King Arthur")

    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]



Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion