欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python边学边练(6)面向对象、class

程序员文章站 2022-06-11 22:06:36
...


参考:b站:覃秉丰,书籍:清华大学出版社《python从入门到精通》
编译环境 python3 jupyter notebook (vscode等编译器对代码进行适当修改即可)

面向对象概述

对象,是一个抽象的概念,表示任意存在的事物。在python中一切都是对象,如字符串,函数,列表等。
类是封装这些对象的载体。
面向对象程序设计具有三大基本特征:**封装、继承、多态**。

类举例-生而为人

人要有名字,年龄,吃饭的动作,思考a+b的过程(就先这么定义四个吧。。)
class person: #“人”类
    name = 'ZK'
    age = 23
    def my_name(self):
        print('my name is : ',self.name)
    def my_age(self):
        print('my age is : ',self.age)
    def eat(self):
        print('I can eat')
    def think(self,a,b):
        print(a+b)

person1 = person()
print(person1.name)
print(person1.age)
print(person1.eat())
print(person1.think(2,8))

结果:

ZK
23
I can eat
None
10
None

Q:为什么会出现None?
参考博文
https://blog.csdn.net/qq_46018836/article/details/105168061
这个问题最简单的方法是使用return关键字
解决方法:

class person: #“人”类
    name = 'ZK'
    age = 23
    def my_name(self):
        print('my name is : ',self.name)
    def my_age(self):
        print('my age is : ',self.age)
    def eat(self):
       return 'I can eat'
    def think(self,a,b):
       return a+b

person1 = person()
print(person1.name)
print(person1.age)
print(person1.eat())
print(person1.think(2,8))

结果:

ZK
23
I can eat
10

创建__init__()方法

class person_n: #“人”类
    def __init__(self,name,age): #外部引入对象
        self.name = name
        self.age = age
    def my_name(self):
        print('my name is : ',self.name)
    def my_age(self):
        print('my age is : ',self.age)
    def eat(self):
       return 'I can not eat'
    def think(self,a,b):
       return a-b

person2= person_n('ZKK',25)
print(person2.name)
print(person2.age)
print(person2.eat())
print(person2.think(2,8))

运行结果:

ZKK
25
I can not eat
-6

类调用函数

person3= person_n(name='ZKKK',age=55)
person3.my_name()

结果:

my name is :  ZKKK

类的继承

class person: #“人”类
    def __init__(self,name='ZK',age = 18): #外部引入对象
        self.name = name
        self.age = age
    def my_name(self):
       return str('my name is : ')+self.name
    def my_age(self):
       return str('my age is : ')+self.age
    def eat(self):
       return 'I can not eat'
    def think(self,a,b):
       return a-b

class student(person): #student子类继承person父类,子类可以使用父类对象,同时子类自己也可以定义对象
    def __init__(self,grade,school):
        super().__init__() #父类初始化
        self.grade = grade
        self.school = school
        self.score = 100
        print('student init')
    def learn(self):
        return 'I am learning'
    def my_school(self):
        return str('my school is : ')+self.school
        
stu = student(grade=2,school='SHU')
print(stu.my_name())
print(stu.think(10,24))
print(stu.school)
print(stu.learn())
print(stu.my_school())

结果:

student init
my name is : ZK
-14
SHU
I am learning
my school is : SHU