文章目录
一、方法没有重载,方法的动态性
1、方法没有重载
#Python 中没有方法的重载。定义多个同名方法,只有最后一个有效
class Person:
def say_hi(self):
print("hello")
def say_hi(self,name):
print("{0},hello".format(name))
p1 = Person()
p1.say_hi()
p1.say_hi("xiaoxiao")
2、方法的动态性
class Person:
def work(self):
print("努力上班")
def play_game(s):
print("{0}在玩游戏".format(s))
def work2(s):
print("努力上班,好好工作,赚大钱")
Person.play = play_game
p = Person()
p.work()
p.play()
Person.work = work2
p.work()
二、私有属性
1.私有属性
#测试私有属性
class Employee:
def __init__(self,name,age):
self.name = name
self.__age = age
e = Employee("XIAOZHU",18)
print(e.name)
print(e._Employee__age)
三、私有方法
#测试私有方法
class Employee:
__company = "chenguxyuan"
def __init__(self,name,age):
self.name = name
self.__age = age
def __work(self):
print("好好工作")
print("年龄:{0}".format(self.__age))
print(Employee.__company)
e = Employee("XIAOZHU",18)
print(e.name)
print(e._Employee__age)
print(dir(e))
e._Employee__work()
print(Employee._Employee__company)
四、@property 装饰器
二级标题
class Employee:
@property
def salary(self):
print("salary...")
return 100000
emp1 = Employee()
print(emp1.salary)
class Employee:
def __init__(self,name,salary):
self.__name = name
self.__salary = salary
def get_salary(self):
return self.__salary
def set_salary (self, salary):
if 1000<salary<50000:
self.__salary = salary
else:
print("录入错误,应该再1000 到50000之间")
emp1 = Employee("xiaozhu",30000)
print(emp1.get_salary())
emp1.set_salary(-20000)
print(emp1.get_salary())
class Employee:
def __init__(self,name,salary):
self.__name = name
self.__salary = salary
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self,salary):
if 1000 < salary < 50000:
self.__salary = salary
else:
print("录入错误,应该再1000 到50000之间")
# def get_salary(self):
# return self.__salary
# def set_salary (self, salary):
# if 1000<salary<50000:
# self.__salary = salary
# else:
# print("录入错误,应该再1000 到50000之间")
emp1 = Employee("xiaozhu",30000)
# print(emp1.get_salary())
# emp1.set_salary(-20000)
# print(emp1.get_salary())
print(emp1.salary)
emp1.salary = 2000
print(emp1.salary)
五、继承
Python 支持多重继承,一个子类可以继承多个父类。继承的语法格式如下:
class 子类类名(父类 1[,父类 2,…]):
类体
如果在类定义中没有指定父类,则默认父类是 object 类。也就是说,object 是所有类的父类,里面定义了一些所有类共有的默认实现,比如:new()。
定义子类时,必须在其构造函数中调用父类的构造函数。调用格式如下:
父类名.init(self, 参数列表)
1、简单的继承
class Person:
pass
class Student(Person):
pass
print(Student.mro())
2、继承的基本使用
class Person:
def __init__(self,name,age):
self.name = name
self.__age = age
def say_age(self):
print("年龄,我也不知道")
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
print(Student.mro())
s = Student("xiaozhu",18,60)
s.say_age()
print(s.name)
print(s.age)
class Person:
def __init__(self,name,age):
self.name = name
self.__age = age
def say_age(self):
print("年龄,我也不知道")
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
print(Student.mro())
s = Student("xiaozhu",18,60)
s.say_age()
print(s.name)
# print(s.age)
print(s._Person__age)
3、方法的重写
#测试方法的重写
class Person:
def __init__(self,name,age):
self.name = name
self.__age = age
def say_age(self):
print("我的年龄:",self.__age)
def say_introduce(self):
print("我的名字是{0}".format(self.name))
class Student(Person):
def __init__(self,name,age,score):
Person.__init__(self,name,age)
self.score = score
def say_introduce(self):
"""重写父类的方法"""
print("报告老师,我的名字是{0}".format(self.name))
s = Student("xiaozh",18,80)
s.say_age()
s.say_introduce()
4、object 根类
class Person: #默认继承object类
def __init__(self,name):
self.name = name
def __str__(self):
return "名字是:{0}".format(self.name)
p = Person("xiaozhu")
print(p)
5、多重继承
不推荐使用
#多重继承
class A:
def aa(self):
print("aa")
class B:
def bb(self):
print("bb")
class C(B,A):
def cc(self):
print("cc")
c = C()
c.cc()
c.bb()
c.aa()
六、多态
1、多态简单使用
class Man:
def eat(self):
print("饿了,吃饭了")
class Chinese(Man):
def eat(self):
print("中国人用筷子吃饭")
class English(Man):
def eat(self):
print("英国人用叉子吃饭")
class Indian(Man):
def eat(self):
print("印度人用手吃饭")
def manEat(m):
if isinstance(m,Man):
m.eat()
else:
print("不能吃饭")
manEat(Chinese())
manEat(English())
七、运算符重载
#测试运算符的重载
class Person:
def __init__(self,name):
self.name = name
def __add__(self, other):
if isinstance(other,Person):
return "{0}--{1}".format(self.name,other.name)
else:
return "不是同类对象,不能相加"
def __mul__(self, other):
if isinstance(other,int):
return self.name*other
else:
return "不是同类对象,不能相乘"
p1 = Person("xiaozhu")
p2 = Person("xiaoxiaozhu")
x = p1 + p2
print(x)
print(p1*3)
八、特殊属性
class A:
def aa(self):
print("aa")
class B:
def bb(self):
print("bb")
class C(B,A):
def __init__(self,nn):
self.nn = nn
def cc(self):
print("cc")
c = C(3)
c.cc()
c.bb()
c.aa()
print(dir(c))
print(c.__dict__)
print(c.__class__)
print(C.__base__)
print(C.mro())
print(A.__subclasses__())
结果:
[‘class’, ‘delattr’, ‘dict’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘getstate’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘module’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘setattr’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘weakref’, ‘aa’, ‘bb’, ‘cc’, ‘nn’]
{‘nn’: 3}
<class ‘main.C’>
<class ‘main.B’>
[<class ‘main.C’>, <class ‘main.B’>, <class ‘main.A’>, <class ‘object’>]
[<class ‘main.C’>]
九、继承对象的浅拷贝和深拷贝
import copy
class MobilePhone:
def __init__(self,cpu,screen):
self.cpu = cpu
self.screen = screen
class CPU:
def calculate(self):
print("算个 12345")
print("CPU 对象:", self)
class Screen:
def show(self):
print("显示一个好看的画面)
print("屏幕对象:",self)
c = CPU()
s = Screen()
m = MobilePhone(c,s)
m.cpu.calculate()
n = m #两个变量,但是指向了同一个对象
print(m,n)
m2 = copy.copy(m) #m2 是新拷贝的另一个手机对象
print(m,m2)
m.cpu.calculate()
m2.cpu.calculate() #m2 和 m 拥有了一样的 cpu 对象和 screen 对象
m3 = copy.deepcopy(m)
m3.cpu.calculate() #m3 和 m 拥有不一样的 cpu 对象和 screen对象
结果:
CPU 对象: <main.CPU object at 0x000002A1FCD15F10>
<main.MobilePhone object at 0x000002A1FCD16050> <main.MobilePhone object at 0x000002A1FCD16050>
<main.MobilePhone object at 0x000002A1FCD16050> <main.MobilePhone object at 0x000002A1FCD16210>
计算,算个 12345
CPU 对象: <main.CPU object at 0x000002A1FCD15F10>
计算,算个 12345
CPU 对象: <main.CPU object at 0x000002A1FCD15F10>
计算,算个 12345
CPU 对象: <main.CPU object at 0x000002A1FCD16190>
十、组合
二级标题
#测试组合
class A1:
def say_a1(self):
print("a1,a1,a1")
class B1(A1):
pass
b1 = B1()
b1.say_a1()
class A2:
def say_a2(self):
print("a2,a2,a2")
class B2:
def __init__(self,a):
self.a = a
a2 = A2()
b2 = B2(a2)
b2.a.say_a2()
“is-a”关系,我们可以使用“继承”。从而实现子类拥有的父类的方法和属性。“is-a”关系指的是类似这样的关系:狗是动物,dog is animal。狗类就应该继承动物类。
“has-a”关系,我们可以使用“组合”,也能实现一个类拥有另一个类的方法和属性。”has-a”关系指的是这样的关系:手机拥有 CPU。 MobilePhone has a CPU。
class MobilePhone:
def __init__(self,cpu,screen):
self.cpu = cpu
self.screen = screen
class CPU:
def calculate(self):
print("计算,算个 12345")
print("CPU 对象:", self)
class Screen:
def show(self):
print("显示一个好看的画面,亮瞎你的钛合金大眼")
print("屏幕对象:",self)
c = CPU()
s = Screen()
m = MobilePhone(c,s)
m.cpu.calculate()
m.screen.show()
十一、设计模式_工厂模式实现
#测试工厂模式
class CarFactory:
def create_car(self,brand):
if brand == "奔驰":
return Benz()
elif brand == "宝马":
return BMW()
elif brand == "比亚迪":
return BYD()
else:
return "未知品牌无法创建"
class Benz:
pass
class BMW:
pass
class BYD:
pass
factory = CarFactory()
c1 = factory.create_car("奔驰")
c2 = factory.create_car("比亚迪")
print(c1)
print(c2)
#单例模式
class MySingleton:
__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 MySingleton.__init_flag:
print("init....")
self.name = name
MySingleton.__init_flag = False
a = MySingleton("aa")
print(a)
b = MySingleton("bb")
print(b)