Python:面向对象

时间:2023-03-08 23:18:05
Python:面向对象

面向过程:根据业务逻辑从上到下写垒代码

面向对象:对函数进行分类和封装

函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可

类:用来描述具有相同属性和方法的对象的集合,定义了该集合中每个对象共有的属性和方法。

方法重写:如果父类继承的方法不能满足子类的需求,可以对父类进行修改

创建类:

class 类名:
成员变量
成员函数

例:

class MyClass:     #定义类
n1 = 123456
n2 = 'abc'
def fun(self):
return 'hello python!'
c = MyClass()
print(c.n1) #调用MyClass里面的变量n1
print(c.n2) #调用MyClass里面的变量n2
print(c.fun()) #调用MyClass里面的函数fun()

输出结果:

123456
abc
hello python!

定义有初始状态的类:类定义了 __init__() 方法的话,类的实例化操作会自动调用 __init__() 方法。__init__() 方法可以有参数,参数通过 __init__() 传递到类的实例化操作上

def __init__(self):
self.data = []

例:

class Province:
a = 123
def __init__(self,name,capital):
self.Name = name
self.Capital = capital hb = Province('河北','石家庄')
hn = Province('河南','郑州') print(hb.Capital)
print(Province.a)

输出结果:

石家庄
123

类的使用:

例1:

class information:
name = ''
age = 0
weight = 0
def __init__(self,n,a,w):
self.name = n
self.age = a
self.weight = w
def result(self):
print("%s:I'am %s years old now!"%(self.name,self.age)) i = information('pingy',20,130)
print(i.result())

输出结果:

pingy:I'am 20 years old now!

例2:

class temp:
def __init__(self):
pass
def __del__(self): #构建函数,在执行结束后都会执行这条函数
print('我要释放了!')
def func(self):
print('go')
def __call__(self):
print('call') f1 = temp()
f1.func() #调用func函数
f1() #相当于执行__call__函数,只是跟普通定义的函数调用方式不一样而已

输出结果:

go
call
我要释放了!

类的继承:

例1:普通函数继承&继承函数内容并修改内容

class father:
def __init__(self):
pass
def func(self):
print('class father')
def Bad(self):
print('抽烟,喝酒') class son(father): #继承父类
def __init__(self):
pass
def temp(self):
print('class son')
def Bad(self): #在继承父类后并修改父类
print('打篮球') res = son()
res.temp() #调用子类中的函数
res.func() #调用父类中的函数
res.Bad() #修改父类函数的内容

输出结果:

class son
class father
打篮球

例2:普通函数继承,保存继承函数内容并增加内容

class father:
def __init__(self):
pass
def func(self):
print('class father')
def Bad(self):
print('抽烟,喝酒') class son(father): #继承父类
def __init__(self):
pass
def temp(self):
print('class son')
def Bad(self):
father.Bad(self)
print('打牌') #继承父类中Bad函数,并增加内容 res = son()
res.temp() #调用子类中的函数
res.func() #调用父类中的函数
res.Bad() #继承父类中Bad函数,并增加内容

输出结果:

class son
class father
抽烟,喝酒
打牌

例3:构建函数的继承

新式类继承方法和旧式类继承方法区别:(如下面两个例子:)

#在2.0版本中:
>>> class A:
def __init__(self):
print 'A'.center(10,'*')
def save(self):
print 'save from A' >>> class B(A):
def __init__(self):
print 'B'.center(10,'*') >>> class C(A):
def __init__(self):
print 'C'.center(10,'*')
def save(self):
print 'save from C' >>> class D(B,C):
def __init__(self):
print 'D'.center(10,'*') >>> c = D()
****D*****
>>> c.save()
save from A
#在3.0版本中:
class A:
def __init__(self):
print('A'.center(10,'*'))
def save(self):
print('save from A') class B(A):
def __init__(self):
print('B'.center(10,'*')) class C(A):
def __init__(self):
print('C'.center(10,'*'))
def save(self):
print('save from C') class D(C,B):
def __init__(self):
print('D'.center(10,'*')) c = D()
c.save()

输出结果:

****D*****
save from C

例4:旧式类继承方法

class father:
def __init__(self):
print('father.__init__') class son(father): #继承父类
def __init__(self):
print('son.__init__')
print('line'.center(30,'*'))
father.__init__(self) #调用父类构建函数__init__函数 res = son()

输出结果:

son.__init__
*************line*************
father.__init__

例5:新式类继承方法

#新式类继承方法
class father(object):
def __init__(self):
print('father.__init__') class son(father): #继承父类
def __init__(self):
print('son.__init__')
print('line'.center(30,'*'))
super(son,self).__init__() res = son()

输出结果:

son.__init__
*************line*************
father.__init__

例6:

class information:    #定义基本属性
name = ''
age =0
weight = 0 def __init__(self,n,a,w): #定义构造方法
self.name = n
self.age = a
self.weight = w
def res(self):
print("%s: I'm %s years old and the weight is %s" %(self.name,self.age,self.weight)) class other(information): #单继承方法
grade = ''
def __init__(self,n,a,w,g):
information.__init__(self,n,a,w)
self.grade = g
def res(self):
print("%s: I'm %s years old ,The weight is %s kg,grade %s" %(self.name,self.age,self.weight,self.grade)) c = other('telnet',15,45,8)
print(c.res())

输出结果:

telnet: I'm 15 years old ,the weight is 45 kg,grade 8

多继承:

class father:   #创建父类
name = ''
age = 0
def __init__(self,n,a): #定义构造方法
self.name = n
self.age = a
def display(self):
print("姓名:%s,年龄:%s。" %(self.name,self.age)) result = father('jay1',10)
print(result.display()) print("我是分割线".center(30,'*')) class son1(father): #创建子类1,调用父类
weight = 0
def __init__(self,n,a,w):
self.weight = w
father.__init__(self,n,a)
def display(self):
print("姓名:%s,年龄:%s,体重:%s" %(self.name,self.age,self.weight)) result = son1('jay2',20,50)
print(result.display()) print("我是分割线".center(30,'+')) class son2(son1): #创建子类2,调用子类1
address = ''
def __init__(self,n,a,w,add):
self.address = add
son1.__init__(self,n,a,w)
def display(self):
print("姓名:%s,年龄:%s,体重:%s,地址:%s。" %(self.name,self.age,self.weight,self.address)) result = son2('jay3',30,60,'BeiJing')
print(result.display()) print("我是分割线".center(30,'-')) class others: #创建另外一个类others,没有调用任何类
job = ''
def __init__(self,j):
self.job = j
def display(self):
print("工作:%s" %self.job)
result = others('IT')
print(result.display()) print("我是分割线".center(30,'=')) class another(son2,others): #创建另一个类another,调用子类2和others类,多重调用
email = ''
def __init__(self,n,a,w,add,j,e):
self.email = e
son2.__init__(self,n,a,w,add)
others.__init__(self,j)
def display(self):
print("姓名:%s,年龄:%s,体重:%s,地址:%s,工作:%s,邮件:%s" %(self.name,self.age,self.weight,self.address,self.job,self.email)) result = another('jay4',40,70,'shanghai','HR','123@qq.com')
print(result.display())

输出结果:

姓名:jay1,年龄:10。
************我是分割线*************
姓名:jay2,年龄:20,体重:50
++++++++++++我是分割线+++++++++++++
姓名:jay3,年龄:30,体重:60,地址:BeiJing。
------------我是分割线-------------
工作:IT
============我是分割线=============
姓名:jay4,年龄:40,体重:70,地址:shanghai,工作:HR,邮件:123@qq.com

 类的私有方法:

class Test:
__secretCount = 0 #私有变量
publicCount = 0 #公开变量 def counter(self):
self.__secretCount += 1
self.publicCount += 1
print(self.__secretCount) result = Test()
print(result.counter())
print('Line'.center(30,'+'))
print(result.publicCount)
print('Line'.center(30,'*'))
print(result.__secrctCount)

输出结果:

1
+++++++++++++Line+++++++++++++
1
*************Line*************
Traceback (most recent call last):
print(result.__secrctCount)
AttributeError: 'Test' object has no attribute '__secrctCount' #报错,私有变量不能访问。

类的专有方法:

class Test:
name = 'pingy'
age = 20
weight = 50
address = 'BeiJing'
res = Test() res.job = 'IT' #新增一个对象和属性
1.print(res.job)
2.print(getattr(res,'weight')) #查看对象'weight'的属性
3.print(hasattr(res,'address')) #查看类中是否存在'address'对象,如果存在返回True,否则返回False
del Test.address #删除address对象
4.print(hasattr(res,'address'))
5.print(delattr(res,'job')) #删除job
6.print(hasattr(res,'job')) #不存在job对象,del和delattr都是删除对象!
res.name = 'echo' #修改name属性
7.print(res.name)

输出结果:

1.IT
2.50
3.True
4.False
5.None
6.False
7.echo

类的专用方法总结:

hasattr(res, 'age')    # 如果存在 'age' 属性返回 True。
getattr(res, 'age') # 返回 'age' 属性的值
setattr(res, 'age', 8) # 添加属性 'age' 值为 8
delattr(res, 'age') # 删除属性 'age'

内置类属性:

__dict__ : 类的属性(包含一个字典,由类的数据属性组成)
__doc__ :类的文档字符串
__name__: 类名
__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
__bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)