SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
Because Python is dynamically typed, it doesn’t really care about interfaces - all it cares about is applying operations to objects (in fact, Java’s interfacekeyword would be wasted in Python). This means that inheritance in Python is different from inheritance in C++ or Java, where you often inherit simply to establish a common interface. In Python, the only reason you inherit is to inherit an implementation - to re-use the code in the base class.
If you’re going to inherit from a class, you must tell Python to bring that class into your new file. Python controls its name spaces as aggressively as Java does, and in a similar fashion (albeit with Python’s penchant for simplicity). Every time you create a file, you implicitly create a module (which is like a package in Java) with the same name as that file. Thus, no package keyword is needed in Python. When you want to use a module, you just say importand give the name of the module. Python searches the PYTHONPATH in the same way that Java searches the CLASSPATH (but for some reason, Python doesn’t have the same kinds of pitfalls as Java does) and reads in the file. To refer to any of the functions or classes within a module, you give the module name, a period, and the function or class name. If you don’t want the trouble of qualifying the name, you can say
from module import name(s)
Where “name(s)” can be a list of names separated by commas.
You inherit a class (or classes - Python supports multiple inheritance) by listing the name(s) of the class inside parentheses after the name of the inheriting class. Note that the Simple class, which resides in the file (and thus, module) named SimpleClass is brought into this new name space using an import statement:
# PythonForProgrammers/Simple2.py
from SimpleClass import Simple
class Simple2(Simple):
    def __init__(self, str):
        print("Inside Simple2 constructor")
        # You must explicitly call
        # the base-class constructor:
        Simple.__init__(self, str)
    def display(self):
        self.showMsg("Called from display()")
    # Overriding a base-class method
    def show(self):
        print("Overridden show() method")
        # Calling a base-class method from inside
        # the overridden method:
        Simple.show(self)
class Different:
    def show(self):
        print("Not derived from Simple")
if __name__ == "__main__":
    x = Simple2("Simple2 constructor argument")
    x.display()
    x.show()
    x.showMsg("Inside main")
    def f(obj): obj.show() # One-line definition
    f(x)
    f(Different())
Note
you don’t have to explicitly call the base-class constructor if the argument list is the same. Show example.
Note
(Reader) The note above is confusing. Did not understand. IMHO one still needs to invoke the base-class constructor if the argument is the same. Probably one needs to state that in case the base class constructor functionality continues to be adequate for the derived class, then a new constructor need not be declared for the derived class at all.
Simple2 is inherited from Simple, and in the constructor, the base-class constructor is called. In display( ), showMsg( ) can be called as a method of self, but when calling the base-class version of the method you are overriding, you must fully qualify the name and pass self in as the first argument, as shown in the base-class constructor call. This can also be seen in the overridden version of show( ).
In __main__, you will see (when you run the program) that the base-class constructor is called. You can also see that the showMsg( ) method is available in the derived class, just as you would expect with inheritance.
The class Different also has a method named show( ), but this class is not derived from Simple. The f( ) method defined in __main__ demonstrates weak typing: all it cares about is that show( ) can be applied to obj, and it doesn’t have any other type requirements. You can see that f( ) can be applied equally to an object of a class derived from Simple and one that isn’t, without discrimination. If you’re a C++ programmer, you should see that the objective of the C++ template feature is exactly this: to provide weak typing in a strongly-typed language. Thus, in Python you automatically get the equivalent of templates - without having to learn that particularly difficult syntax and semantics.