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 exa开发者_JS百科mple:
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).
Magic. Python-specific magic, to be exact; other languages may (and frequently do) choose to do it differently.
It can be. In Python,
Class.method(obj)
is the same asobj.method()
whenobj
is an instance ofClass
.__init__()
is a special case though.
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.
精彩评论