Python - 类

  • 类的创建

# 类的创建使用class,类名的首字母要大写,没有指定继承的类时,默认继承object类
'''
    #简写:
    class Animails:
        def __init__(arg):
            pass
'''
class Animals(object):
    def __init__(arg1,arg2):
        self.arg1 = arg1
        self.arg2 = arg2
    def fun(self):
        print(self.arg1,self.arg2)

  • 对象方法、静态方法、类方法

一般情况下,如果没有声明静态方法或类方法,则对象方法在调用时,需要实例化,如果 有声明静态方法或类方法,可以使用类名.方法()直接调用。

class School:
    def __init__(self, arg):
        self.arg = arg
    # 普通的类方法需要实例化,并传递参数才能正常调用,否则报错
    def fun(self):
        return 'This is general function.'
        
    # 静态方法不用传递参数
    @staticmethod
    def prt_s():
        return 'This is staticmethod.'
    
    # 类方法可以直接调用,可以不传参数
    @classmethod
    def prt_c(self):
        return 'This is classmethod'

print(School.prt_c())
print(School.fun('Mys'))
print(School.prt_s())

        

  • 继承与方法重写

# 创建父类
class School:
    def __init__(self,name,flag):
        self.name = name
        self.flag = flag

    def lives(self):
        if self.flag == 'stu':
            return f'Student {self.name} lives in dormitory'
        elif self.flag == 'teach':
            return f'Teacher {self.name} lives in lodging house'
        else:
            return None

# 在括号中指定继承的类
class Student(School):
    def __init__(self,name,age):
        self.name = name
        self.age = age
        flag = 'stu'
        # 继承父类School
        School.__init__(self, self.name, flag=flag)    

    def stu_age(self):
        return f'Student {self.name} is {self.age} years old.'

class Teacher(School):
    def __init__(self,name,age):
        self.name = name
        self.age = age
        flag = 'teach'
        # 继承父类School
        School.__init__(self, self.name,flag='teach')

    def teacher_age(self):
        return f'Teacher {self.name} is {self.age} years old.'
    
# 将父类的方法重写
    def lives(self):
        return 'This is new'
        
stu = Student('Make',10)
print(stu.stu_age())
print(stu.lives())
print('-----------------------------------')
teacher = Teacher('Jock',20)
print(teacher.teacher_age())
print(teacher.lives())

  • 多态

class Animal:
    def eat(self):
        print("动物会吃~")

class Cat(Animal):
    def eat(self):
        print("猫喜欢吃鱼~")

class Dog(Animal):
    def eat(self):
        print("狗喜欢吃骨头~")

class Person:
    def eat(self):
        print("人喜欢吃米饭~")

def fun(obj):       #函数用于调用方法
    obj.eat()

fun(Cat())
fun(Dog())
person = fun(Person())



  • 浅拷贝&深拷贝

import copy

class Computer:
    def __init__(self,disk,cpu):
        self.disk = disk
        self.cpu = cpu

class Disk:
    pass

class Cpu:
    pass

cpu1 = Cpu()
print("cpu1_id:",id(cpu1))

cpu2 = copy.copy(cpu1)      #使用copy函数复制出来的实例的id与源实例的id不同
print("cpu2_id:",id(cpu2))

#浅拷贝:只复制新建一个实例对象的,子对象Disk()和Cpu()不复制
disk = Disk()
cpu = Cpu()
computer01 = Computer(disk,cpu)     #将子对象传给Computer对象
print("computer01_id:",id(computer01))
print("computer01_disk_id:{0},\tcomputer01_cpu_id:{1}".format(id(computer01.disk),id(computer01.cpu)))
computer02 = copy.copy(computer01)
print("computer02_id:",id(computer02))
print("computer02_disk_id:{0},\tcomputer02_cpu_id:{1}".format(id(computer02.disk),id(computer02.cpu)))

#深拷贝:源对象和子对象都会被拷贝,所以看到computer03、disk、cpu都是新的ID
computer03 = copy.deepcopy(computer01)
print("computer03_id:",id(computer03))
print("computer03_disk_id:{0},\tcomputer03_cpu_id:{1}".format(id(computer03.disk),id(computer03.cpu)))

  • 特殊属性与方法

#特殊属性与方法
#print(dir(object))     #dir()可以查看对象有哪些特殊属性方法

class Human(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

class woman(Human):
    def __init__(self,woman):
        self.woman = woman

class man(Human):
    def __init__(self,man):
        self.man = man

class Addname(Human):
    def __init__(self,name,age,other):
        Human.__init__(self,name,age)
        self.other = other
    def __add__(self):
        return self.name + self.other
    def __len__(self):
        return len(self.name)       
        #指定name长度,方便实例化时,可以获取到实例的name长度

human = Human("Make",20)
print(human.name,human.age)
print(human.__dict__)       #查看实例human的字典数据
print(Human.__dict__)       #查看Human的字典类型
print(human.__class__)      #查看human所属类
print(Human.__class__)      #查看Human的类
print(Human.__base__)       #查看Human的父类
print(Human.__mro__)        #查看Human的类结构
print(Human.__subclasses__())   #查看Huamn的子类列表

a = 10
b = 20
c = a + b
d = a.__add__(b)
print(c,d)

h1 = Addname("Jacket",30,"李四")
print(h1.__add__())

lst1 = [11,22,33,44]
print(len(lst1))        #len用计算有多少个字符
print(len(h1))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值