面向对象
1、面向对象和面向过程
拿洗衣服举个例子
【面向过程】 是你按照"衣服放水里——放洗衣粉——搓衣服——冲洗"这样的步骤,一步步自己完成
【面向对象】 就是你将衣服放进洗衣机里,洗衣机会帮你洗,不需要你管洗衣服的步骤
2、类(class)——对具有相同属性和方法的一组对象的描述或定义
【类中函数——方法】
class 类名():
‘’‘…’‘’ 说明文字,方便程序员更直观的知道类的作用
def init(self):
pass 表示后面暂时没有更多信息,可在后续编程中完善
…
class Washer():
def __init__(self,color,type,function):
self.color = color#属性
self.type = type
self.function = function
def Wash(self):
mes = "您的洗衣机颜色为 "+self.color\
+" 是 "+self.type +"\n您要使用的功能是 "+self.function
return mes
my_washer = Washer("黑色","滚筒式","漂加脱")
print(my_washer.type)
result = my_washer.Wash()
print(result)
输出结果为:
滚筒式
您的洗衣机颜色为 黑色 是 滚筒式
您要使用的功能是 漂加脱
【修改属性】
指定默认值
self.属性名 = default
修改属性值
对象名.属性名 = 修改值
class Washer():
def __init__(self,color,type,function):
self.color = color
self.type = type
self.function = function
self.count = 100
def Wash(self):
mes = "您的洗衣机颜色为 "+self.color\
+" 是 "+self.type +"\n您要使用的功能是 "+self.function
return mes
my_washer = Washer("黑色","滚筒式","漂加脱")
print(my_washer.count)
my_washer.count = 90
print(my_washer.count)
输出结果为:
100
90
【还可以通过方法来修改属性值】
3、继承
【A类继承B类,那么A类自动获得B类中的所有属性和方法,B类称为父类,A称为子类】
class B类名():
def init(self,…):
…
def …
class A类名(B类名):
def init(self,…):
super().init()
…
def …