开始学习面向对象,可以说之前的学习和编程思路都是面向过程的,从上到下,一步一步走完。

如果说一个简单的需求,用面向过程实现起来相对容易,但是如果在日常生产,面向对象就可以发挥出他的优势了。

程序的可扩展性,代码的可读性,以及后期的优化和二次开发,都是面向过程不可相比的,下面整理一下知识点。

类:

#Authon Ivor
class dog(object):
#公有变量,如果有私有变量,优先调用私有,如果没有调用公有
age = 8 def __init__(self,name,type):
self.name = name
self.type = type def bark(self):
print("%s is barking,wang.wang..wang..." % self.name)
self.type = "wang.wang..wang.." def get_type(self):
print("{0} 's type is {1}".format(self.name,self.type)) d = dog("lovely","Teddy")
d2 = dog("diudiu","田园犬") d.bark()
d2.get_type()
d.age = 10
print(d.age)
print(d2.age)
dog.age = 9
print(d.age)
print(d2.age) def bark2():
print("bark")
d.bark = bark2
d.bark()

继承:

#Authon Ivor

class Person(object):
def __init__(self,name,age):
self.name = name
self.age = age
self.sex = "F"
def talk(self):
print("I'm a person!") class BlackPerson(Person):
#先继承,再重构
def __init__(self,name,age,strength):
Person.__init__(self,name,age)
self.strength = strength
#重构函数
def talk(self):
print("I am BlackMan!")
class WhitePerson(Person):
pass B = BlackPerson("YoYo",22,"Strong")
B.talk()

继承2:

#Authon Ivor
class SchoolMember(object):
'''基类'''
member = 0
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex =sex
self.enroll() def enroll(self):
print("[%s] has just enrolled ." % self.name)
SchoolMember.member += 1 def tell(self):
print("info %s".center(20,"-") % self.name )
for k,v in self.__dict__.items():
print("%s:%s" % (k,v))
print("info %s".center(20,"-") % self.name )
#析构函数
def __del__(self):
print("\033[31;1mmember [%s] is dead!\033[0m" %self.name)
SchoolMember.member -= 1 class Teacher(SchoolMember):
'''讲师类'''
def __init__(self,name,age,sex,salary,tuition):
# 新式类写法
# super(Teacher,self).__init__(name,age,sex)
# 经典类写法
SchoolMember.__init__(self,name,age,sex)
self.salary = salary
self.tuition = tuition class Student(SchoolMember):
'''学生类'''
def __init__(self,name,age,sex,tuition):
SchoolMember.__init__(self,name,age,sex)
self.amount = 0
self.tuition = tuition s1 = Student("Hebe",18,"F","Python")
t1 = Teacher("Yoyo",22,"F",10000,"Python")
t1.tell()
print(SchoolMember.member)
del s1
print(SchoolMember.member)

封装补充:

#Authon Ivor

class F1(object):
def __init__(self,arg):
self.a = arg class F2(F1):
def __init__(self,arg):
self.b = arg class F3(F2):
def __init__(self,arg):
self.c = arg o1 = F1("Alex")
o2 = F2(o1)
o3 = F3(o2) #######通过o3调取到Alex#######
print(o3.c.b.a)

继承补充:

#Authon Ivor
class F1(object):
def a1(self):
print("F1a1") class F2(F1):
def a1(self):
self.a2()
print("F2a1")
def a2(self):
print("F2a2") class F3(F2): def a2(self):
print("F3a2") #优先调取obj自身的方法
obj = F3()
obj.a1()
05-11 22:08