面向函数编程:将某功能的代码封装为一个函数,使用时仅调用函数;
(2+3)*2-1 jian(multi(add(2,3),2),1)
面向对象编程:对函数进行分类和封装….
class people: # 经典类 class People(object): # 新式类,object类是所有类的基类/父类 def __init__(self,name,age): # 构造函数,当实例化对象时自动调用; self.name = name # 属性(给实例对象绑定属性) self.age = age def run(self): # 方法 print "running...." def __del__(self): print "deleteing......" # 析构函数,删除实例化对象时自动调用; class Student(People): # Student是子类,继承People这个父类; pass p1 = People("jerry",7) p1.run()
封装:把内容统一放在一个地方,看成一个整体,(实例化对象self和类的属性绑定在一起);
访问封装内容的两种方式:
self.name p1 = People("westos",17) p1.age
继承:子承父业
- 新名词:基类/派生类, 父类/子类, 新式类和经典类
- 多继承:
新式类: 广度优先继承;(python2.x和python3.x均支持)
经典类:深度优先继承;(python2.x支持,python3.x没有经典类)
- 注意:
类的方法中可以传递一个对象;
class A(object): def eat(self): print ("A eating") class B(A): def eat(self): print ("B eating") class C(A): def run(self): print ("C running") q1 = C() q1.eat() A eating
如果子类调用的方法,子类没有,父类有,运行父类;
如果子类调用的方法,子类有,父类也有,只运行子类的;
class A(object):
def eat(self):
print ("A eating")
class B(A):
def eat(self):
print ("B eating")
class C(A):
def run(self):
print ("C running")
q1 = B()
q1.eat()
B eating
面向对象进阶
类变量,全局变量,在内存中只存储一份; 普通的对象属性,每个对象中都需要存储一份;
class People(object):
country = "China"
def __init__(self,name,age):
self.name = name
self.age = age
print (People.country)
p1 = People("redhat",18)
print (p1.name,p1.age,p1.country)
方法
实例化方法:第一个参数为self(实例化本身); 类方法:第一个参数是cls(类本身);通过@classmethod装饰器实现; 静态方法:第一个参数既不是self也不是cls;通过@staticmethod方法实现;
class datetest(object):
def __init__(self,year=0,month=0,day=0):
self.year = year
self.month = month
self.day = day
def show_date(self):
return "Year:{}\nMonth:{}\nDay:{}\n".format(self.year,self.month,self.day)
@classmethod
def get_str_date(cls,s):
year, month, day = map(int,s.split("-"))
date1 = cls(year,month,day)
return date1
d = datetest.get_str_date("2017-3-3")
print d.show_date()
特殊属性
类的特殊成员
class Goods(object):
def __init__(self):
self.old_price = 100
self.discount = 0.4
@property
def price(self):
new_price = self.old_price * self.discount
return new_price
g = Goods()
print (g.price)