Inheritance and polymorphism
We have just mentioned, you can create a new class on the basis of existing classes, a practice which is to make a class where it will directly inherit properties and methods from another class down, thereby reducing write duplicate code. Provide information to inherit what we call the parent class, also called the superclass or base class; subclass inherits get what we call information, also called the derived class or derived class. In addition to the subclass inherits the properties and methods of the parent class provides, you can also define your own unique properties and methods, so more power sub analogy parent has, in the actual development, we often use to replace the subclass object a parent object, object-oriented programming is that a common behavior, corresponding to the principle known as the principle of replacement Richter. Let's look at an example of inheritance.
class Person(object):
"""人"""
def __init__(self,name,age):
self._name = name
self.age = age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
@age.setter
def grade(self, grade):
self._grade = grade
def study(self, course):
print('%s的%s正在学习%s.' % (self._grade, self._name, course))
class Teacher(Person)
def __init__(self, name, age, title):
super().__init__(name, age)
self._title = title
@property
def title(self):
return self._title
@title.setter
def title(self, title):
self._title = title
def teach(self, course):
print('%s%s正在讲%s.' % (self._name, self._title, course))
def main():
stu = Student('王大锤', 15, '初三')
stu.study('数学')
stu.watch_av()
t = Teacher('骆昊', 38, '老叫兽')
t.teach('Python程序设计')
t.watch_av()
if __name__ == '__main__':
main()
子类在继承了父类的方法后,可以对父类已有的方法给出新的实现版本,这个动作称之为方法重写(override)。通过方法重写我们可以让父类的同一个行为在子类中拥有不同的实现版本,当我们调用这个经过子类重写的方法时,不同的子类对象会表现出不同的行为,这个就是多态(poly-morphism)。
列表生成式
a = [x for x in range(100000000000) if x % 2==0]
优点:计算速度快,因为一次性已经加载到内存中了,适合数据量不太大的情况
缺点:占用内存
生成器
a = (x for x in range(10000000000) if x % 2 ==0)
优点:节约内存空间
缺点:计算速度慢,因为要生成
继承代码:
class A(object):
def __init__(self):
self.a = 100
def A1(self):
print("A1)
在类名中写上继承的类
class B(A):
def init(self):
A.init(self)
self.b = 200
def B1(self);
print(‘B1')
装饰器代码
def deco(func):
def warp(a,b):
print(a+b)
return func(a,b)
return warp
@deco
def qa(a,b):
print("a,b")
qa(100,20)
装饰器参数代码
#装饰器将前面两个数字的求和,函数本身第三个数乘上这个和。
def qa(func):
def warp(num1,num2,num3):
num = num1 + num2
return func(0,num,num3)
return warp
@qa
def SUM(num1,num2,num3):
print(num1,num2,num3)
print(num2*num3)
SUM(5,8,9)
闭包
def foo():
l = []
def bar(i):
l.append(i)
return l
return bar
f1 = foo()
res1 = f1(1)
print(res1)
res2 = f1(2)
print(res2)
输出结果是
[1]
[1, 2]