David542
David542

Reputation: 110083

Basic question on Object Oriented programming in Python

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).

Upvotes: 1

Views: 256

Answers (2)

Michael Dillon
Michael Dillon

Reputation: 32392

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.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

  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.

Upvotes: 4

Related Questions