Python6

  • 实例方法

1.定义实例方法时,第一个参数必须为self,和前面一样,self指当前的实例对象
2.调用实例方法,不需要也不能给self传参数,self由解释器自动传参

  • 其他操作

dir(obj)可以获得对象的所有属性、方法
obj._dict_对象的属性字典
pass空语句
isinstance(对象,类型)判断“对象”是不是“指定类型”

类对象、类属性、类方法

#type模具类
class Student:
    pass #空语句

print(type(Student))
s1=Student
print(type(s1))
  • 类属性

类属性的定义方式:
class 类名:
类变量名=初始值

class Student:
    company="SXT"
    count=0

    def __init__(self,name,score):
        self.name=name  #实例属性
        self.score=score
        Student.count=Student.count+1

    def say_score(self):  #实例方法
        print("我的公司是:",Student.company)
        print(self.name,"的分数是:",Student.count)

s1=Student("张三",88)  #s1是实例对象,自动调用__init__()方法
s1.say_score()
print("一共创建{0}个Student对象".format(Student.count))

在这里插入图片描述

  • 类方法
    在这里插入图片描述
class Student:
    company="SXT"
    
    def __init__(self,name,age):
        self.name=name
        self.age=age
        
    @classmethod  #这个方法只属于类
    def printCompany(cls):
        print(cls.company)
    #   print(self.company)#类方法和静态方法不能调用实例属性、self不一定存在

Student.printCompany()
  • 静态方法
    在这里插入图片描述
class Student:
    company = "SXT"

    @staticmethod   #静态方法
    def add(a,b):
        print("{0}+{1}={2}".format(a,b,(a+b)))
        return a+b

Student.add(1,8)

__del__方法(析构函数)

在这里插入图片描述

class Person:
    def __del__(self):
        print("销毁对象{0}".format(self))

p1=Person()
p2=Person()

del p2
print("程序结束")  #p1也会被销毁

__call__方法和调用对象

  • 定义了_call_方法的对象,称为“可调用对象”,即该对象可以像函数一样被调用
class SalaryAccount:
    def __call__(self, salary):
        print("算工资了...")
        yearSalary=salary*12
        daySalary=salary/27.5
        hourSalary=daySalary/8
        return dict(yearSalary=yearSalary,daySalary=daySalary,hourSalary=hourSalary)

s=SalaryAccount()
print(s(30000))
  • 方法没有重载

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

  • 方法动态性(方法也是对象)
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()

封装

  • 私有属性、私有方法
    在这里插入图片描述
class Employee:
    __company="SXT"
    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("gaoqi",18)
print(e.name)
#print(e.age)错误访问
print(e._Employee__age)
print(dir(e))
e._Employee__work()
print(Employee._Employee__company)

@property装饰器

  • @property可以将一个方法的调用方式变成“属性调用”。
使用set/get方法
class Person:

    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("录入错误")

p1=Person("gaoqi",20000)
print(p1.get_salary())
p1.set_salary(-222)
使用property
class Person:
    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("录入错误")

p1=Person("gaoqi",20000)
print(p1.salary)
p1.salary=2000
print(p1.salary)

继承

在这里插入图片描述

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

#Student->Person->object
print(Student.mro())
s=Student("gg",14,88)
s.say_age()
print(s._Person__age)  #调用私有属性
print(s.name)

print(dir(s))

类成员的继承和重写

在这里插入图片描述

class Person:
    def __init__(self,name,age):
        self.name=name
        self.__age=age #私有属性
    def say_age(self):
        print("我的年龄:",self.__age)
    def say_name(self):
        print("我的名字:", self.name)
        
class Student(Person):
    def __init__(self,name,age,score):
        Person.__init__(self,name,age)   #必须显式的调用父类的方法,不然解释器不会去调用
        self.score=score

    #重写父类的方法
    def say_age(self):
        print("大家好我的年龄:", self._Person__age)
    def say_name(self):
        print("报告老师。我的名字:", self.name)
        
s=Student("hh",25,90)
s.say_age()
s.say_name()

object根类_dir()

  • 通过类的方法mor()或者类的属性_mor_可以输出这个类的继承层次结构
class A:
    pass
class B(A):
    pass
class C(B):
    pass
print(C.mro())

在这里插入图片描述

  • Python支持多继承,如果父类中有相同名字的方法,在子类没有指定父类名时,解析器将“从左到右”按顺序搜索
class A:
    def say(self):
        print("aa")
class B:
    def say(self):
        print("bb")
class C(A,B):
    pass

c=C()
c.say()  #aa

重写__str__方法

在这里插入图片描述

class Person: #默认继承object
    def __init__(self,name):
        self.name=name
    def __str__(self):
        return "名字是{0}".format(self.name)

p=Person("ss")
print(p)

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()

多态

在这里插入图片描述

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(n):
    if isinstance(n,Man):
        n.eat()
    else:
        print("不能吃饭")
manEat(Chinese())
  • 特殊方法和运算符的重载
    在这里插入图片描述

在这里插入图片描述

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 "不是同类对象,不能相加"
p1=Person("ss")
p2=Person("hh")

x=p1+p2
print(x)
  • 特殊属性

在这里插入图片描述

对象的浅拷贝和深拷贝

在这里插入图片描述

#测试对象的浅拷贝、深拷贝
import  copy
class MobilePhone:
   def __init__(self,cpu,screen):
       self.cpu=cpu
       self.screen=screen

class CPU:
    def caluate(self):
        print("算123")

class Screen:
    def show(self):
        print("蓝色")

#测试变量赋值
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)

#测试深复制
m3=copy.deepcopy(m1)
print(m1,m1.cpu,m1.screen)
print(m3,m3.cpu,m3.screen)

组合

在这里插入图片描述

class A1:
    def say_a1(self):
        print("a1,a1")

class B1():
    def __init__(self,a):
        self.a=a

a1=A1()
b1=B1(a1)
b1.a.say_a1()

设计模式

  • 工厂模式
class CatFactory:
     def craet_car(self,brand):
         if brand=="奔驰":
             return Benz()
         elif brand=="宝马":
             return BMV()
         elif brand=="比亚迪":
             return BYD()
         else:
             return  "未知品牌"
class Benz:
    pass
    
class  BMV:
    pass

class BYD:
    pass
    
factory=CatFactory()
c1=factory.craet_car("奔驰")
print(c1)
  • 单例模式
    在这里插入图片描述
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")
b=MySingleton("bb")  #a,b目前是同一个对象
print(a)
print(b)
  • 工厂变成单例

class CatFactory:
    __obj=None
    __init_flag=True
    def craet_car(self, brand):
        if brand == "奔驰":
            return Benz()
        elif brand == "宝马":
            return BMV()
        elif brand == "比亚迪":
            return BYD()
        else:
            return "未知品牌"

    def __new__(cls, *args, **kwargs):
        if cls.__obj == None:
            cls.__obj = object.__new__(cls)
        return cls.__obj

    def __init__(self):
        if CatFactory.__init_flag:
            print("init  factory......")
            CatFactory.__init_flag = False
class Benz:
    pass


class BMV:
    pass


class BYD:
    pass

factory = CatFactory()
c1 = factory.craet_car("奔驰")
c2=factory.craet_car("宝马")
print(c1)
print(c2)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值