Discuss / Python / 静态vs动态的地方不是很懂。请问如果是静态程序会怎样,会有什么不同?

静态vs动态的地方不是很懂。请问如果是静态程序会怎样,会有什么不同?

Topic source

静态vs动态的地方不是很懂。请问如果是静态程序会怎样,哪会有什么不同?

class Animal(object):   #编写Animal类
    def run(self):
        print("Animal is running...")

class Dog(Animal):  #Dog类继承Amimal类,没有run方法
    pass

class Cat(Animal):  #Cat类继承Animal类,有自己的run方法
    def run(self):
        print('Cat is running...')
    pass

class Car(object):  #Car类不继承,有自己的run方法
    def run(self):
        print('Car is running...')

class Stone(object):  #Stone类不继承,也没有run方法
    pass

def run_twice(animal):
    animal.run()
    animal.run()

run_twice(Animal())
run_twice(Dog())
run_twice(Cat())
run_twice(Car())
run_twice(Stone())

皮皮皮MHL

#2 Created at ... [Delete] [Delete and Lock User]

我的理解是这样的:

对于动态语言,参数的类型是自动判断的,不管你是什么类,只要你的类或者父类用用run这种方法就可以使用run_twice这个函数,如果没有,运行时会报错

对于静态语言,参数的类型是在编译前规定好的,只能识别相应的类和其父类,如果有一个其他类与这个函数的传入参数类没有继承关系就不能调用这个函数,编译时就会报错

总结:动态语言在执行时才会做参数检查,而静态语言在编译时就会检查,并且静态语言没有Python这种自动判断类型的特性

皮皮皮MHL

#3 Created at ... [Delete] [Delete and Lock User]
class Animal(object):
    def run(self):
        print('animal is running ...')

class Dog(Animal):
    def run(self):
        print('Dog is running ...')

class Cat(Animal):
    def run(self):
        print('Cat is running ...')

#dog cat 继承了 animal 中已有的方法,如果有了新的同名方法则会覆盖
#dog cat 的实例 既是 dog cat 类 也是 animal 类
def run_twice(Animal):
    Animal.run()
    Animal.run()
#这个函数animal的子类的实例也可以用,而且不需要修改函数
'''开闭原则:
对扩展开放:允许新增Animal子类
对修改封闭:不需要修改依赖Animal类型的run_twice()等函数'''
#鸭子类型
class Timer(object):
    def run(self):
        print('start ...')
timer_t = Timer()
run_twice(timer_t)#即使timer()不是Animal的子类,但是同样可以使用run_twice函数

附上代码方便理解

闻窗一如

#4 Created at ... [Delete] [Delete and Lock User]

例如java会对传入的参数做类型检查,如果不是同一类型就会报错:

class Animal{

public void run(){

System.out.print("animal is  running");

}

}

class Dog extends Animal{

public void run(){

System.out.print("Dog is  running");

}

}

class Stone{

public void run(){

System.out.print("^ _ ^");

}

}

/**

*Animal animal传入的参数类型,不是animal或其子类就会报错

*/

public void test(Animal animal){

animal.run()

}


  • 1

Reply