python 继承

[root@node01 scan]# pwd
/root/scan


[root@node01 scan]# cat a1.py 
from lib.pfwx.Dog import *
a=Dog()
print a
print type(a)
a.run()
print a.fun1()


[root@node01 scan]# cat lib/pfwx/Dog.py
from Animal import *
class Dog(Animal):
   def fun1(self):
       print '---Dog is running---'
   def fun2(self,a):
      print a*a



[root@node01 scan]# cat lib/pfwx/Animal.py
class Animal(object):
    def run(self):
        print 'Animal is running...'
[root@node01 scan]# 




[root@node01 scan]# python a1.py 
<lib.pfwx.Dog.Dog object at 0x7f8e5852f710>
<class 'lib.pfwx.Dog.Dog'>
Animal is running...
---Dog is running---
None
9
None


这个时候Animal类和Dog类在同一级目录:

[root@node01 scan]# cd lib/pfwx/
[root@node01 pfwx]# ls -ltr *py
-rw-r--r-- 1 root root  28 Oct 20 19:00 Cat.py
-rw-r--r-- 1 root root   0 Oct 21 12:16 __init__.py
-rw-r--r-- 1 root root  78 Oct 21 14:50 Animal.py
-rw-r--r-- 1 root root 135 Oct 21 15:58 Dog.py



如果 模块不在同一级目录下呢?

[root@node01 pfwx]# pwd
/root/scan/lib/pfwx

[root@node01 pfwx]# cat Dog.py
from base.Animal import *
class Dog(Animal):
   def fun1(self):
       print '---Dog is running---'
   def fun2(self,a):
      print a*a
  



[root@node01 pfwx]# cat base/Animal.py
class Animal(object):
    def run(self):
        print 'Animal is running...'


注意每个目录必须有__init__.py文件

原文地址:https://www.cnblogs.com/hzcya1995/p/13349455.html