属性
定义类
class 类名:
class Person(): #或者 class Person(object): object代表所有类的父类
#属性
name="zs"
#初始化方法
#def __init__(self):
#self.sex = 33
def __init__(self, sex):
self.sex = sex
#私有属性
__pwd = "123456"
#给私有属性提供get和set方法
def setPwd(self, pwd):
self.__pwd = pwd
def getsetPwd(self):
return self.__pwd
#定义方法
def say(self):
#print("{真好看")
print(f"{self.name}真好看")
print(self)
# 类方法
@classmethod
def sleep(cls):
#print("{正在睡觉")
print(f"{cls.name}正在睡觉")
# 静态方法
@staticmethod
def playDD():
print("正在打豆豆")
-
定义方法
-
定义初始化方法
-
私有属性
-
类方法
-
类方法
对象
对象名 = 类名()
person = Person()
person2 = Person()
print(person)
print(person2)
案例代码
class Person():
# pass
name = "zs"
sex = "女"
# 定义方法
def test(self):
print("世界真美好")
# 定义初始化方法
# def __init__(self):
# self.remark = "gym"
def __init__(self, abc):
self.abc = abc
#定义私有属性
__pwd = "666666"
#给私有属性提供get和set方法
def setPwd(self,pwd):
self.__pwd = pwd
def getPwd(self):
return self.__pwd
#类方法
@classmethod
def sleep(cls):
print("okok")
#静态方法
@staticmethod
def sleep2():
print("okok2")
#实例化对象
person = Person("123")
person2 = Person("456")
# person.name = "ls"
# Person.name = "ww"
# person.age = 18
# print(person.age)
# print(person2.age)
# print(person.name)
# print(person2.name)
# print(Person.name)
# person.test()
# print(person.remark)
# print(person.abc)
# person.setPwd("888") #赋值
# print(person.getPwd()) #取值/调用
# person.sleep()
# Person.sleep()
# person.sleep2()
# Person.sleep2()
继承
可以继承多个父亲,但是如果父亲中有相同的属性或者方法时,以第一个父亲为准
如果想调用具体父亲的属性和方法
具体父亲的名字.属性名
具体父亲的名字.方法名
如何查看一个类的继承关系
print(Son.mro)
案例代码
"""
继承
"""
# 定义父类
class Father(object):
money = 2222.22
def cook(self):
print("会炒菜")
def eat(self):
print("会吃")
class Mother(object):
money = 22222.22
def cook(self):
print("会煮面条")
def playMJ(self):
print("打麻将")
class Son(Mother, Father):
# money = 22.22
def cook(self):
# 调用父类的cook方法
# 01
# Father.cook(self)
# Mother.cook(self)
# 02
#super().cook()
print("煮泡面")
son = Son()
print(son.money)
son.cook()
# son.eat()
# son.playMJ()
# 查看类的继承关系
# print(Son.__mro__)
多态
案例代码
"""
多态
水:
气体:
液体:
固体:
"""
class Water(object):
def use(self):
pass
class Gas(Water):
def use(self):
print("这是气体的水,可以用来蒸饺子")
class Yt(Water):
def use(self):
print("这是液体的水,可以用来煮饺子")
class Gt(Water):
def use(self):
print("这是固体的水,可以用来冻饺子")
class Person(object):
def cook(self, water):
water.use()
person = Person()
gas = Gas()
yt = Yt()
gt = Gt()
person.cook(gt)