介绍
与大多数面向对象的编程语言一样,python也是一门面向对象的解释型语言。与C++、Java等语言不同的是:python在面向对象编程时,其语法与其它语言有一定的不同。本次就来对python语言的面向对象编程的一些性质进行简单的探讨。
Python类相关介绍:
- 类的创建与继承:
class Student:
python中定义类使用class关键字+类名的形式定义一个类。与Java相同的是,object类是所有类的基类(所有类默认继承object类)。python使用class关键字+类名(父类名)的形式表示继承,也就是说上述代码默认与下面代码等价
class Student(object):
- 类属性:
在类中声明的属性,且该属性不在构造函数 __init __ 中,则为类属性,可以给直接被类本身调用,也可以由实例化对象调用。 - 对象实例属性:
在类中声明的属性,且该属性在构造函数 __init __ 中,则为对象实例属性,不能给直接被类本身调用,必须由实例化对象调用。 - 类方法:
在类中使用classmethod修饰符修饰的方法称为类方法,可以给直接被类本身调用,也可以由实例化对象调用。 - 静态方法:
在类中使用staticmethod修饰符修饰的方法称为类方法,可以给直接被类本身调用,也可以由实例化对象调用。
代码说明(注释详细~):
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 10:22:24 2021
python中类相关的基础知识介绍
@author: yuanlin
"""
class Student():
native_var="native1" #类属性
def __init__(self,name,age): #实例属性
self.name = name
self.age = age
def toString(self,name,age): #打印实例属性self.name/self.age(属性值与对象实例绑定)
print(self.name+"\t"+str(self.age)+"!!!")
def toString1(self,name,age): #打印实例属性name/age(属性值未与对象实例绑定)
print(name+"\t"+str(age)+"!!!")
@classmethod #类方法,方法第一个参数cls自动绑定Student类本身,可类调用或对象实例调用
def printInfo (cls):
print('类方法info: ', cls)
@staticmethod #静态方法,方法不与类自动绑定,可类调用或对象实例调用
def printInfo1 (info):
print('静态方法info: ', info)
if __name__ == "__main__": #主函数
stu1=Student("stu1",20)
stu2=Student("stu2",30)
stu1.toString(stu1.name, stu1.age)
stu1.toString(stu2.name, stu2.age) #属性值与对象实例stu1绑定,还是打印stu1属性值
stu1.toString1(stu1.name, stu1.age)
stu1.toString1(stu2.name, stu2.age) #属性值未与对象实例绑定,打印stu2属性值
print("--------------------------------")
print(stu1.native_var)
print(stu2.native_var)
Student.native_var="native2" #通过类修改类属性值,所有对象对应的类属性值均被修改
print(stu1.native_var)
print(stu2.native_var)
stu1.native_var="native3" #通过对象实例修改类属性值,仅该对象对应的类属性值均被修改
print(stu1.native_var)
print(stu2.native_var)
print("--------------------------------") #类与实例对象均可直接调用类方法和静态方法
Student.printInfo()
Student.printInfo1("hello world!")
stu1.printInfo()
stu1.printInfo1("hello world!")
运行结果
类的继承与方法重写
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 14:11:09 2021
@author: Zuo
"""
# 方法的重写
# 当我们调用一个对象的方法时
# 会优先去当前对象中寻找是否具有该方法,如果有则直接调用
# 如果没有则去对象的父类中寻找,如果父类中有则直接调用父类中的方法
# 如果还是没有则去父类中的父类中寻找,以此类推,直到找到object
# 如果始祖父类也没有, 就报错
class Person:
def eat(self):
print('Person eat~~~')
class Student(Person):
def eat(self):
print('Student eat~~~~')
stu = Student()
stu.eat()
运行结果
类的多继承与方法执行顺序
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 14:11:09 2021
@author: Zuo
"""
# 类的多继承:
# 如果在当前类中 找到方法,就直接执行,不再搜索
# 如果没有找到,就按照父类的继承顺序查找下一个类中是否有对应的方法,如果找到,就直接执行,不再搜索
# 如果找到最后一个类,还没有找到方法,程序报错
class Person:
def eat(self):
print('Person eat~~~')
class Animals:
def eat(self):
print('Animals eat~~~')
class Student(Animals,Person):
def sleep():
print("Student sleep~~~")
stu = Student()
stu.eat()
上述代码中Student类的继承顺序为Animals类和Person类,且Student类自身未重写eat()方法,故调用的是Animals类中的eat()方法,结果为:
反之,我们变换一下Student类的继承顺序,仅需将源代码中修改一处,修改如下:
class Student(Person,Animals):
运行结果为:
希望我的总结对你们有帮助,博客中相关问题欢迎询问探讨,相互学习。QQ:1476154032,以上。