`
前言:本文主要讲解了类的定义、神奇方法,并用实例一一说明。
`提示:以下是本篇文章正文内容,下面案例可供参考
一、python的类是什么?
古人云:物以类聚,人以群分,类简单来说是一些具有相同属性的事物统称,在python中通过定义类,可实现面向对象编程(相对于面向过程编程)。
二、类的定义方式(三种)
第一种(object是所有类的祖宗类):
class 类名(object):
如:class student(object):
print('定义了一个类名为学生的类')
第二种:
class 类名():
如:class student():
print('定义了一个类名为学生的类')
第三种:
class 类名:
如: class student:
print('定义了一个类名为学生的类')
特别注意:类内可一无所有,当类内没有任何东西时,用pass表示
class student:
pass
三、类的神奇方法(3个)
1.初始化对象属性
例:class student():
def __init__(self,name,sex):
self.sex = sex
self.name = name
self.__scoder=85
2.打印对象名,默认返回(return)字符串
例:def __str__(self):
return f'性别:{self.sex}'
3.默认当对象调用次数为0时被回收
def __del__(self):
print( f'del this object{self.name}')
四、类的一般书写格式及其调用方式(例)
class phone: #定义类
def open(self): #定义方法
print('开机啦!')
def close(self): #定义方法
print('关机啦')
def take_profile(self): #定义方法
print('自拍吧!')
apple13=phone() #建立对象
apple14=phone() #建立对象
apple13.open() #调用方法
apple13.close() #调用方法
apple13.take_profile() #调用方法
五、实例:运用了神奇方法
class student(): #定义类
def __init__(self,name,age): #神奇方法之一:初始化对象属性
self.age = age
self.name = name
self.__score=85 #私有属性(属性名前会加双下划线:__)
def get_score(self,name): #私有属性无法直接被获得时,可用函数间接获取
if name=='sue':
print(f'分数是{self.__score}')
else:
print('不得这个分。')
def __str__(self): #神奇方法之一:打印对象名时,默认返回字符串
return f'年龄:{self.age}'
def __del__(self): #神奇方法之一:当对象调用次数为0时,默认被回收。
print( f'删除这个对象{self.name}')
def study(self):
print(f'{self.age}的{self.name}好好学习,天天向上')
def __score(self): #私有方法(方法名前会加双下划线:__)
print('请打印分数名单')
sue=student('sue',16) #建立对象
sue.study() #调用方法
print(sue.name,sue.age) #打印属性
print(sue) #打印对象名,自动调用了__str__
sue.get_score('sue') #调用方法
#注意:类的私有属性和私有方法不能被子类和对象直接继承。
最后,关于类的神奇方法,还有其它的,大家可自行deepseek!
学习编程,一起努力!加油!