1.动态方法_代码示例
class Person:
def work(self):
print("努力上班!")
def play_game(self):
print("{0}玩游戏".format(self))
def work2(s):
print("好好工作,努力上班!")
Person.play = play_game # 给类动态增加方法
Person.work = work2 # 给类动态增加方法
p = Person()
p.play() # 输出:<__main__.Person object at 0x000001A81D68BC48>玩游戏
p.work() # 输出:好好工作,努力上班!
2.私有属性_代码示例
class Employee:
__company = "usn"
def __init__(self, name, age):
self.name = name
self.__age = age # 两个下划线开头的属性是私有的(private)
def __work(self): # 私有方法(方法也是一种属性)
print(self.__age) # 私有变量对内是公开的
print(self.__company) # 输出:usn
emp = Employee("ski", 15)
print(emp.name) # 输出:ski
print(emp._Employee__age) # 输出:15。通过“_类名__私有属性(方法)名”访问私有属性(方法)
print(emp._Employee__company) # 输出:usn
emp._Employee__work()
3.property_代码示例
class Employee:
def __init__(self, name, salary):
self.name = name
self.__salary = salary # 使用@property属性必须私有吗?
@property #相当于 salary 属性的 getter 方法
def salary(self):
return self.__salary
@salary.setter
def salary(self, salary):
if 1000 < salary < 8000: # 提高代码鲁棒性
self.__salary = salary
else:
print("请输入1000~8000的薪水")
# def salary_getter(self): # 实现getter和setter代码
# return self.salary_getter()
# def salary_setter(self, salary):
# if 1000<salary<8000:
# self.salary = salary
# else:
# print("请输入1000~8000的薪水")
emp = Employee('ski', 3000)
# emp.salary_setter(10000) # 不使用@property时设置salary
emp.salary = 5000 # 使用@property后设置salary
print(emp.salary) # 输出:5000
4.继承_代码示例
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age # 父类私有,子类不能直接使用
class Student(Person): # 子类继承了父类除构造方法之外的所有成员。
def __init__(self, name, age, score):
Person.__init__(self, name, age) # 共享父类的资源
self.score = score
stu = Student('ski', 13, 60)
print(dir(stu)) # 查看stu的属性,注意方法也是一种属性
print("name:{0}, age:{1}, score:{2}".format(stu.name, stu._Person__age, stu.score))
# 输出:['_Person__age', '__class__', ···'name', 'score']
# 输出:name:ski, age:13, score:60
5.重写_代码示例
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
def introdution(self): # 被“重写”覆盖的对象
print("my name is {0}".format(self.name))
class Student(Person):
def __init__(self, name, age, score):
Person.__init__(self, name, age)
self.score = score
def introdution(self): # 与父类同名效果等同于“重写”了父类
print("my name is {0}, i am {1}".format(self.name, self._Person__age))
stu = Student('ski', 18, 60)
stu.introdution()
print(Student.mro()) # 者类的方法或(属性__mro__)可以输出这个类的继承层次结构。
#输出:[<class '__main__.Student'>, <class '__main__.Person'>, <class 'object'>]
6.super_代码示例
class Person:
def introduction(self):
print("i am person class")
class Student(Person):
def introduction(self):
# Person.introduction(self) # 调用父类的 introduction()方法,要传self??
super().introduction() # 通过 super()调用父类的方法,不用传self??
print("i am student class")
Student().introduction() # 输出:i am person class i am student class
7.多态_代码示例
class Man: # 多态(polymorphism)是指同一个方法调用由于对象不同可能会产生不同的行为。
def eat(self):
print("饿了么?")
class Chinese(Man):
def eat(self):
print("用筷子吃饭")
class English(Man):
def eat(self):
print("用刀叉吃饭")
def man_eat(m): # 多态是方法的多态,属性没有多态
if isinstance(m, Man): #传入的对象不同,执行的方法也不同。
m.eat()
else:
print("不能吃饭")
man_eat(Chinese()) # 输出: 用筷子吃饭
man_eat(English()) # 输出: 用刀叉吃饭
8.符号重载_代码示例
class Person: # 测试运算符的重载
def __init__(self, name):
self.name = name
def __add__(self, other): # 重写了 + 号方法。
if isinstance(other, Person): # other表示类型
return "{0}-{1}".format(self.name, other.name)
else:
return "非同类对象,不能相乘"
def __mul__(self, other): # 重写了 * 号方法
if isinstance(other, int):
return other*self.name
else:
return "不是同类不能相乘"
p = Person("blu")
p1 = Person("ski")
print(p+p1) # 输出:blu-ski
print(p*3) # 输出:blublublu
9.拷贝_代码示例
import copy
class MobilePhone:
def __init__(self, cpu, screen): #类也是对象,也可以作为参数传
self.cpu = cpu
self.screen = screen
class Cpu:
def calculate(self):
print("计算数字")
print("cpu对象:", self)
class Screen:
def show(self):
print("显示画面")
print("screen对象:", self)
c1 = Cpu()
s1 = Screen()
m1 = MobilePhone(c1, s1) # 类作为参数传递
m1.screen.show()
m1.cpu.calculate()
m2 = copy.copy(m1) # 浅拷贝
print(m1, m2)
m3 = copy.deepcopy(m1) # 深拷贝
print(m1, m3)
10.组合_代码示例
class MobilePhone:
def __init__(self, cpu, screen): # 类也是一种对象,可以作为示例的属性调用
self.cpu = cpu
self.screen = screen
class Cpu:
def calculate(self):
print("cpu计算")
class Screen:
def show(self):
print("屏幕显示画面")
m = MobilePhone(Cpu(), Screen()) # 通过这种方式组合,可实现功能和继承一样。
m.cpu.calculate() # 输出:cpu计算
m.screen.show() # # 输出:屏幕显示画面
11.工厂模式_代码示例
class PhoneFactory: # 工厂模式
def create_phone(self, brand):
if brand == "华为":
return HW() # 返回类对象, 这个类没写括号也行??
elif brand == "小米":
return MI()
class HW:
print("华为手机造好了")
class MI:
print("小米手机造好了")
factory = PhoneFactory()
factory.create_phone("华为")
factory.create_phone("小米")
12.单例模式_代码示例
class Factory:
__obj = None
__init_flag = True
def __new__(cls, *args, **kwargs):
if cls.__obj == None:
cls.__obj = object.__new__(cls)
return cls.__obj
def __init__(self, name):
if self.__init_flag == True:
self.name = name
print(self.name)
self.__init_flag = False
f1 = Factory("手机厂") # 输出:手机厂
f2 = Factory("电脑厂") # 不输出
print(f1, f2) # 输出:<__main__. at 0x174866A6FC8> ,<__main__.at 0x174866A6FC8>