开发者

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


  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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜