Python是门动态语言
- 动态体现在能够在程序运行过程中对变量类型进行修改。例如下面这个例子:
a = 100
print(a)
def test():
print("---test---")
a = test
a()
- 运行结果如下。原来
a
指向一个整形数据类型,在程序运行至后面的代码,a
又指向了一个函数体,这就是动态的体现。
------
- 动态的另外一个体现就是能够在程序运行过程中向定义好的类中添加实例属性、类属性、类方法和静态方法。下面用代码进行展示:
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
laowang = People("laowang", 18)
print(laowang.name)
print(laowang.age)
laowang.sex = "male"
print(laowang.sex)
laozhang = People("laozhang",20)
print(laozhang.name)
print(laozhang.age)
People.planet = "earth"
print(laowang.planet)
print(laozhang.planet)
@classmethod
def wear(cls):
print("---classmethod ware---")
@staticmethod
def walk():
print("---staticmethod walk---")
People.wear = wear
People.walk = walk
laowang.wear()
laowang.walk()
--- ---
--- ---
- 除了能够动态地添加实例属性、类属性、类方法和静态方法,当然还能够添加实例方法,只是添加的方式有所不同。下面同样使用代码展示:
import types
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print("---%s is eating---"%self.name)
def run(self):
print("---%s is running---"%self.name)
laowang = People("laowang", 18)
laowang.eat()
laowang.run = types.MethodType(run, laowang)
laowang.run()
laozhang = People("laozhang", 20)
laozhang.eat()
--- ---
--- ---
--- ---
__slots__
的作用
- 上面我们讲了Python是一门动态语言,在定义好的类中我们能够随意的添加各种实例属性和方法,这虽然相对于静态语言有很大的优势,但有时也有弊端。当我们不愿意他人随意添加实例属性及方法时,就需要用到
__slots__
。
- 下面用代码进行展示:
import types
class People(object):
__slots__ = ("name","age")
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print("---%s is running---"%self.name)
laowang = People("laowang", 18)
print(laowang.name)
People.planet = "earth"
print(laowang.planet)
Python多态的体现
- 下面用代码来说明Python的多态,这也是在
c++
中定义的多态性:
class Father(object):
def introduce(self):
print("---hello, I'm the father---")
class Son(object):
def introduce(self):
print("---hello, I'm the son---")
def introduce_yourself(instance):
instance.introduce()
human1 = Father()
human2 = Son()
introduce_yourself(human1)
introduce_yourself(human2)
---, ---
---, ---