1

I'm having a hard time grasping the variables inside a method of a Class, and am seeking an explanation of how these work, to help me better understand it.

For example:

inside Time class

def __init__(self, hour,minute, second)
    self.hour = hour
    self.minute = minute
    self.second = second

def print_time(self):
    print '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)

time = Time(h,m,s)
time.print_time()

Where does the change in variable for 'self' occur? Why isn't the method called (what would seem more straight-forward) as: method(var1(subject), var2, var3, var4)? instead of subject.method(var2, var3, var4)? (I know my understanding of this is shaky, and I'm happy to receive corrections if any of my terms are incorrect).

2
  • This code is wrong. Eg. self.x = hour — there is no hour in the available scope. What is print_time? Where is the class definition? Commented Apr 14, 2011 at 2:48
  • ok -- I updated the code. This example is taken from How To Think Like a Computer Scientist (link below). Commented Apr 14, 2011 at 2:53

2 Answers 2

4
  1. Magic. Python-specific magic, to be exact; other languages may (and frequently do) choose to do it differently.

  2. It can be. In Python, Class.method(obj) is the same as obj.method() when obj is an instance of Class. __init__() is a special case though.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd say the "magic" happens in other languages, where words like "this" magically refer to the current instance (sometimes the "this" is even magically added to fields where it fits).
0

Where did you get this wierd code? It does not make sense.

You should look at "How To Think Like a Computer Scientist" which has a code sample similar to what you posted, except that it is correct, and it explains the variable scope. Look at section 15.6 of the above URL.

2 Comments

It's copy and pasted from there, I just changed the variables inside init. The only thing is, I did not include the print_time() method.
You cannot just change the variables like that. Fundamentally, the code from the web, takes three values that are parameters of the init function and copies them to three attributes of the object instance. This relies on the parameter name being used on the right side of the equals sign. The left side name can be anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.