python 继承

继承:

创建一个子类和创建一个类是很相似的,你只需要提供一个或多尔个基类(不是对象)就行了。

实例化:


 其他语言一般都使用new语句来创建实例,不过Python里你只要像调用函数一样调用类的名字就可以了。

Python 用的是"初始化程序"而不是构造函数。

所以名字用的也是__init__,在实例化一个对象时,你需要传入__init__所需的参数。




在OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类

而被继承的类称为基类,父类或者超类


class Animal(object):
    def __init__(self):
        print self
    def run(self,a,b):
        return a + b
##实例化对象
a=Animal()
##调用实例方法
print a.run(3,4)


C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/Django/a9.py
<__main__.Animal object at 0x02177E30>
7



[oracle@node01 web]$ vim Animal.py
[oracle@node01 web]$ pwd
/oracle/python/mycompany/web
[oracle@node01 web]$ ls -ltr Animal.py 
-rw-r--r-- 1 oracle dba 109 Sep  4 16:55 Animal.py


导入模块:

[oracle@node01 python]$ pwd
/oracle/python
[oracle@node01 python]$ cat 91.py 
from   mycompany.web.Animal  import * 
a=Animal()
print a.run(3,4)
[oracle@node01 python]$ python 91.py 
<mycompany.web.Animal.Animal object at 0x7fd6fad09690>
7




继承:
[oracle@node01 web]$ cat Animal.py
class Animal(object):
    def __init__(self):
        print self
    def run(self,a,b):
        return a + b
    def update(self,a,b):
       return a-b



[oracle@node01 python]$ cat 92.py 
from   mycompany.web.Animal  import * 
class Dog(Animal):
  def __init__(self):
        print self
  def run(self,a,b):
     return a+b+9
a=Dog()
print a.run(3,4)
[oracle@node01 python]$ python 92.py 
<__main__.Dog object at 0x7fec3354d7d0>
16






当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。

这样,我们就获得了继承的另一个好处:多态。

[oracle@node01 python]$ cat 92.py 
from   mycompany.web.Animal  import * 
class Dog(Animal):
  def __init__(self):
        print self
  def run(self,a,b):
     return a+b+9
a=Dog()
print a.run(3,4)
print a.update(66,12)
[oracle@node01 python]$ python 92.py 
<__main__.Dog object at 0x7fd2836bf7d0>
16
54

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