zoukankan      html  css  js  c++  java
  • 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文件

  • 相关阅读:
    第二阶段团队绩效评分
    团队冲刺2.9
    团队冲刺2.8
    团队冲刺2.7
    团队冲刺2.6
    团队冲刺2.5
    项目总结以及事后诸葛亮会议
    做什么都队第二阶段绩效评估
    第二阶段冲刺第十天
    第二阶段冲刺第九天
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349455.html
Copyright © 2011-2022 走看看