python - the first class example and method inv...

2338 ワード

In this post, we will first present you with the first definition of the python class and we will explain little on how the method invocation is happening (or with what process the method is found) first let 's see the code.
'''
Created on 2012-11-17

@author: Administrator
file: Circle.py
description: this is a basic class definition , which models Circle. 
'''

class Circle(object):
    '''
    Circle classes
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.radius = 1
    def area(self):
        return self.radius * self.radius * 3.14159
Below is the unit test code that shows how to use the class. 
'''
Created on 2012-11-17

@author: Administrator
'''
import unittest
from Classes.Circle import Circle

class Test(unittest.TestCase):


    def testRadius(self):
        c = Circle()
        c.radius = 3
        assert c.area() == 3 * 3 * 3.14159, "area failed!"
        
    def testRadius_Syntax2(self):
        c = Circle()
        c.radius = 3
        area = Circle.area(c)
        assert area == 3 * 3 * 3.14159, "area failed!"


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testRadius']
    unittest.main()
That it is. how is the method invocated? the process of finding the right method to call is as fllow.
  • Look for the method name in the instance namespace. If a method has been changed or added for this instance, it’s invoked in preference over methods in the class or superclass. This is the same sort of lookup discussed later .
  • If the method isn’t found in the instance namespace, look up the class type class of instance, and look for the method there. In the previous examples, class is Circle—the type of the instance c.
  • If the method still isn’t found, look for the method in the superclasses.
  • When the method has been found, make a direct call to it as a normal Python, using instance as the first argument ofthe function, and shifting all the other arguments in the method invocation one space over to the right. So, instance.method(arg1, arg2, . . .) becomes class.method(instance, arg1, arg2, . . .).