python面向对象

面向对象的简单理解

对象:将数据和数据操作封装到一起,形成一个整体

面向对象:将对象相同的属性和方法抽象成一个类,并组织和处理类与类的关系

那么该如何实现类与类之间的关系呢?

在程序中我们可以使用封装,继承,多态等来实现

面向对象的简单应用

成员变量,类变量,self

self:指向对像实例的地址,将实例对象的变量传给函数中的self,使每个不同实例对象实现更加高效

可见self为当前实例类的返回类型

class Test():
    def self_type_print(self):
        print(self.__class__)#__class__表示类的返回类型
test=Test()
test.self_type_print()
<class '__main__.Test'>

成员变量:是动态变量,随着对象的创建而存在

class Student():
    def __init__(self,a,b):
        self.a=a#成员变量
        self.b=b
        # self.name
    def test(self):
        print(self.a,self.b)
student=Student(1,2)
student.test()
1 2

类变量:也叫静态全局变量,随着类的加载而存在(我们可以发现类变量是静态的,一个实例对象操作的append方法将变量list_data改变了,但是另一个实例对象在使用此变量时仍然受到了上一个实例对象的影响)

class Student():
    list_data=[]#类变量
    def appendtest(self):
        print(self.list_data.append(1))
student1=Student()
student2=Student()

student1.appendtest()

print(student1.list_data)
print(student2.list_data)
[1]
[1]

构造方法

在python中函数__init__()为类的构造方法,当类被实例化时,将动态变量进行初始化。

class Test():
    def __init__(self,a,b):
        self.a=a
        self.b=b
    def print_parameter(self):
        print(self.a,self.b)
test=Test(1,2)
test.print_parameter()
1 2

分装:将现实中的事物分装成类中的属性,变量

#猫和狗都是动物,但是他们生活习性不同,根据面向对象知识我们可以先将它们相同的属性和行为封装起来
#将猫狗相同的属性和行为分装成Animal类
class Animal():
    character="可爱"
    def __init__(self,color,breed,food):
        self.breed=breed
        self.color=color
        self.food=food
    def eat(self):
        print(f"{self.color}颜色{self.breed}喜欢吃{self.food},它们吃饭也有点{self.character}")

继承:继承类属于父类的派生类,拥有父类的公有变量和方法,并能加入新的方法,实现新的功能

#猫类继承动物类
class Cat(Animal):
    def character_cat(self):
        print("这是猫类")
cat=Cat("白","小猫","鱼")
cat.character_cat()
cat.eat()
这是猫类
白颜色小猫喜欢吃鱼,它们吃饭也有点可爱

多态:在封装和继承的基础上,对继承的方法进行重写 或者在类中写多个同名不同参函数进行重载。

#狗类继承动物类
class Dog(Animal):
    def __init__(self, color, breed, food,act):
        self.breed = breed
        self.color = color
        self.food = food
        self.act=act
    def character_dog(self):
        print("这是狗类")
    def eat(self):
        print(f"{self.color}颜色{self.breed}喜欢吃{self.food},它们吃饭也有点{self.character}")
        print(f"他还有些{self.act}")
dog=Dog("黑","小狗","肉","活泼")
dog.character_dog()
dog.eat()
黑颜色小狗喜欢吃肉,它们吃饭也有点可爱
他还有些活泼

学习记录,请多多包涵

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杜小白也想的美

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值