Python 面向对象(中)

在这里插入图片描述
在python中面向对象的三大特征:
封装,继承,多态

1. 析构方法

程序结束后,之后调用析构方法,来释放空间

def __del__(self):
	print("析构方法")

2.单继承

子类继承父类

class animal():
    def eat(self):
        print('吃')

class dog(animal):#继承父类
    def wwj(self):
        print('dog')

d=dog()
d.eat()

3.多继承

class animal():
    def eat(self):
        print('吃')
class fourleg():
	def out(self):
		print('四条腿')

class dog(animal,fourleg):#继承父类
    def wwj(self):
        print('dog')

d=dog()
d.eat()
d.out()
吃
四条腿

重写就是在子类中的方法,会覆盖父类的方法

4.多态

对不同的子类对象有不同的行为表现
要想实现多态必须有两个前提:
1.继承:必须存在继承关系,发生在父类和子类之间
2.重写:子类需要重写父类的方法

class animal():
    def say_who(self):
        print('我是一个动物')

class duck(animal):
    def say_who(self):
        print('我是一个鸭子')

class dog(animal):
    def say_who(self):
        print('我是一个小猫')
duck1=duck()
duck1.say_who()
dog1=dog()
dog1.say_who()
我是一个鸭子
我是一个小猫
def commoninovke(obj):
    obj.say_who()
li=[duck(),dog()]
for item in li:
    commoninovke(item)
我是一个鸭子
我是一个小猫

5 类属性和实力属性

class student:
    name='黎明'  #类属性
    def __init__(self,age):  #实例属性
        self.age=age

lm=student(18)
print(lm.name) #通过实例对象访问类属性
print(lm.age)
print(student.name) #通过类对象访问类属性
print(student.age)
黎明
18
黎明
Traceback (most recent call last):
  File "D:/index.py", line 190, in <module>
    print(student.age)
AttributeError: type object 'student' has no attribute 'age'

在这里插入图片描述

6.类方法和实例方法


class people:
    country='china'
    @classmethod
    def get_country(cls):
        return cls.country # 访问类属性

    @staticmethod
    def getData():
        return people.country


#类方法
print(people.get_country()) #通过类对象调用
print(people.country)
p=people()
print(p.get_country()) # 通过实例对象访问
people.country='chinachina'
print(p.country)

# 静态方法
print(p.getData())
china
china
china
chinachina
chinachina

静态方法中不涉及到类中方法和属性的操作
数据资源能够得到有效的利用

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值