python基础——方法、重载、继承、多态

目录

1、重载

1.1方法的动态性

2、 私有属性和私有方法(实现封装)

3、@property装饰器

3.1将一个方法调用方式变为“属性调用”。

3.2装饰器的用法

4、面向对象的三大特征

4.1继承

4.2方法重写

5、object的根类

6、重写__str()__方法

7、多重继承

8、super()获得分类的定义

9、多态

10、特殊方法和运算符重载

11、特殊属性

12、对象的浅拷贝和深拷贝

13、组合

14、设计模式_工厂模式的实现

14.1工厂模式

14.2 设计模式_单例模式


1、重载

python方法中没有重载,定义多个同名方法,只有最后一个有效


1.1方法的动态性

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.play(p)
Person.work=work2
p.work()
chenhong
18
['_Employee__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

进程已结束,退出代码0

2、 私有属性和私有方法(实现封装)

class Employee:
    def __init__(self,name,age):
        self.name=name
        self.__age=age#私有属性
    def __work(self):#私有方法
        print("好好工作,赚钱娶媳妇")
e=Employee("chenhong",18)
print(e.name)
print(e._Employee__age)
print(dir(e))

C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/测试私有属性.py
chenhong
18
['_Employee__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

进程已结束,退出代码0

class Employee:
    __company="百战程序员"
    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("chenhong",18)
print(e.name)
print(e._Employee__age)
print(dir(e))
e._Employee__work
print(Employee._Employee__company)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/测试私有属性.py
chenhong
18
['_Employee__age', '_Employee__company', '_Employee__work', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
百战程序员

进程已结束,退出代码0

3、@property装饰器

3.1将一个方法调用方式变为“属性调用”。

#测试property最简化的使用
class Employee:
    @property
    def salary(self):
        print("salary run...")
        return 10000
emp1=Employee()
#emp1.salary()
print(emp1.salary)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/测试property.py
salary run...
10000

进程已结束,退出代码0

3.2装饰器的用法

#@property装饰器的用法
class Employee:
    def __init__(self,name,age):
        self.__name=name
        self.__age=age
    @property
    def age(self):
        return self.__age
    @age.setter
    def set_age(self, age):
        if 18 < age < 55:
            self.__age = age
        else:
            print("录入年龄错误,年龄在18-55之间")
''' def get_age(self):
        return  self.__age
    def set_age(self,age):
        if 18<age<55 :
            self.__age=age
        else:
            print("录入年龄错误,年龄在18-55之间")
'''
emp1=Employee("chenhong",19)
print(emp1.age)
emp1.set_age=60
print(emp1.age)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/property的用法.py
19
录入年龄错误,年龄在18-55之间
19

进程已结束,退出代码0

4、面向对象的三大特征

封装(隐藏)

继承

多态

4.1继承

子类(派生类)继承父类(基类)

一个子类可以有多个父类

class Student(Person)

默认为object类

class Person:
    def say_age():
        print("年龄为18")
class Student(Person):
    pass

print(Student.mro())
s=Student
s.say_age()
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/子类和父类.py
[<class '__main__.Student'>, <class '__main__.Person'>, <class 'object'>]
年龄为18

进程已结束,退出代码0
class Person:
    def __init__(self,name,age):
        self.name=name
        self.__age=age#私有属性
    def say_age(self):
        print("年龄为18")
class Student(Person):
    def __init__(self,name,age,score):
        Person.__init__(self,name,age)#必须显示的调用父类初始化方法,不然解释器不会去调用
        self.score=score

print(Student.mro())
s=Student("陈洪",18,90)
s.say_age()
print(s.name)
#print(s.age)
print(dir(s))
print(s._Person__age)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/子类和父类.py
[<class '__main__.Student'>, <class '__main__.Person'>, <class 'object'>]
年龄为18
陈洪
['_Person__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'say_age', 'score']
18

进程已结束,退出代码0

4.2方法重写

#测试方法的重写
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("陈洪",18,90)
s.say_age()
s.say_introduce()

运行结果

C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/方法重写.py
我的年龄 18
报告老师,我的名字是:陈洪

进程已结束,退出代码0

5、object的根类

通过类的方法mro()或者类的属性__mro__可以输出这个类的继承层次结构

class A:
    pass
class B(A):
    pass
class C(B):
    pass
print(C.mro())

[<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

dir()查看对象


6、重写__str()__方法

#测试重写object的__str__()
class Person:#默认继承object类
    def __init__(self,name):
        self.name=name
    def __str__(self):
        return ("我的名字是:{0}".format(self.name))
p=Person("陈洪")
print(p)

我的名字是:陈洪

进程已结束,退出代码0

7、多重继承

一个子类可以继承多个父类,但是不会经常使用,但是会变得很复杂。

python支持多继承,如果父类中有相同名字的方法,在子类没有指定父类名时,解释器将“从左到右 ”按顺序搜索

mro()层次析构

8、super()获得分类的定义

# 测试super(),代表父类的定义,而不是父类的对象
class A:
    def say(self):
        print("A",self)
class B(A):
    def say(self):
        # A.say(self)
        super().say()
        print("B",self)
B().say()
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/super().py
A <__main__.B object at 0x00000170DD7B1FA0>
B <__main__.B object at 0x00000170DD7B1FA0>

进程已结束,退出代码0

9、多态

1、多态是多态的方法,属性没有多态

2、多态的存在有2个必要条件:继承、方法重写

class Man:
    def eat(self):
        print("饿了,吃饭啦!")
class  Chinese(Man):
    def eat(self):
        print("中国人用筷子吃饭")
class Enlish(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(Indian())
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/多态.py
中国人用筷子吃饭
印度人用右手吃饭

进程已结束,退出代码0

10、特殊方法和运算符重载

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("高琪")
p2=Person("陈洪")
x=p1+p2
print(x)
print(p1*3)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/运算符的重载.py
高琪--陈洪
高琪高琪高琪

进程已结束,退出代码0

11、特殊属性

obj.__dict__ 对象的属性字典

obj.__class__ 对象所属的类

class.__bases__类的基类元组(多继承)

class.__base__ 类的基类

class.__mro__ 类层次结构

class.__subclasses() 子类列表

12、对象的浅拷贝和深拷贝

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("screen对象",self)
#测试变量赋值
c1=CPU()
c2=c1
print(c1)
print(c2)
#测试浅复制
s1=Screen()
m1=MobilePhone(c1,s1)
m2=copy.copy(m1)
print(m1,m1.cpu,m1.screen)
print(m2,m2.cpu,m2.screen)
#测试深复制
print("测试深复制-----------")
m3=copy.deepcopy(m1)
print(m1,m1.cpu,m1.screen)
print(m3,m3.cpu,m3.screen)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/测试对象的浅拷贝和深拷贝.py
<__main__.CPU object at 0x0000018678DCDFD0>
<__main__.CPU object at 0x0000018678DCDFD0>
<__main__.MobilePhone object at 0x0000018678DCDF70> <__main__.CPU object at 0x0000018678DCDFD0> <__main__.Screen object at 0x0000018678DCDFA0>
<__main__.MobilePhone object at 0x0000018678DCDD90> <__main__.CPU object at 0x0000018678DCDFD0> <__main__.Screen object at 0x0000018678DCDFA0>
测试深复制-----------
<__main__.MobilePhone object at 0x0000018678DCDF70> <__main__.CPU object at 0x0000018678DCDFD0> <__main__.Screen object at 0x0000018678DCDFA0>
<__main__.MobilePhone object at 0x0000018678DCDCD0> <__main__.CPU object at 0x0000018678DCDC10> <__main__.Screen object at 0x0000018678DCDBB0>

进程已结束,退出代码0

13、组合

#使用继承实现代码的复用
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()
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/测试组合.py
a1,a1,a1
a2,a2,a2

进程已结束,退出代码0

14、设计模式_工厂模式的实现

14.1工厂模式

#测试工厂模式
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)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/工厂模式.py
<__main__.Benz object at 0x000001C65861CFA0>
<__main__.BYD object at 0x000001C65861CF70>

进程已结束,退出代码0

14.2 设计模式_单例模式

#测试工厂模式
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)
C:\Users\86189\anaconda\python.exe C:/Users/86189/PycharmProjects/pythonProject/pythonday8/单例测试.py
init...
<__main__.Mysingleton object at 0x000001D28D6ECFA0>
<__main__.Mysingleton object at 0x000001D28D6ECFA0>
<__main__.Mysingleton object at 0x000001D28D6ECFA0>

进程已结束,退出代码0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值