1.面向对象
2.类和对象
def ...(self,参数列表):
pass #占位符
def ...(self,参数列表):
pass
创建对象:
对象变量 = 类名()
对象.方法名()
def __init__(self): #init方法也称为构造方法,创建对象时为对象初始化成员变量
self.type = "波斯猫" # 公有属性/共有变量
self.name = None
cat1 = Cat() # 取值
print(cat1.type)
cat1.name = "大帅" # 赋值
print(cat1.name)
# 给cat1穿衣服
cat1.cloth = "red" # 独有属性/独有变量
print(cat1.cloth)
4.魔术方法init、str
5.类变量、类方法
class Cat:
subject = "猫科"
def __init__(self,name,color):
self.name = name
self.color = color
def eat(self):
print("小猫爱吃鱼")
print(self.name)
print(Cat.subject)
Cat.show_type() # print(self.show_type())
@classmethod
def show_type(cls):
print("type is none")
print(cls.subject)
print("*" * 20)
cat1 = Cat("大帅", "white")
cat1.eat()
Cat.show_type()
6.静态方法
7. 面向对象三大特性:封装、继承、多态
- __私有
class Card:
def __init__(self):
self.id = None
self.__pwd = None
def get_pwd(self):
return self.__pwd
def set_pwd(self, pwd):
self.__pwd = pwd
def __name(self):
self.__username = None
c = Card()
c.set_pwd("123456")
print(c.get_pwd())
-->123456
class Grandpa:
def sing(self):
print("爷爷唱歌")
class Father(Grandpa):
def sing(self):
print("爸爸擅长唱歌。")
super().sing()
class Mother(Grandpa):
def sing(self):
print("妈妈唱歌很难听。")
super().sing()
class Child(Father, Mother):
def sing(self):
print("在下歌神洞庭湖")
Father.sing(self)
super().sing()
c = Child()
c.sing()
print(Child.__mro__)
# (<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class '__main__.Grandpa'>, <class 'object'>)
class Teacher:
def teach(self):
print("教授知识")
class Driver:
def drive(self):
print("开车")
class Man(Teacher,Driver):
def teach(self):
print("教授Python知识")
def drive(self):
print("开小轿车")
class Demo:
def play(self,driver):
driver.drive()
def study(self,teacher):
teacher.teach()
# 方案一:创建司机对象
d = Driver()
# 方案二:创建了一个具有司机特征的对象
man = Man()
demo = Demo()
demo.play(man)
demo.study(man)
更多免费技术资料可关注:annalin1203