#----------------面向对象----------------
# 成员方法:方法中有self
# 类方法 : 无self
# __代表私有
class people:
name = ''
age = 0
__weight = 0 #私有属性
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说: 我 %d 岁。" %(self.name,self.age))
p = people('runoob',10,30)
p.speak()
# 继承
class student(people):
grade = ''
def __init__(self,n,a,w,g):
people.__init__(self,n,a,w)
self.grade = g
def speak(self):
print('{} 说: 我 {} 岁。在读{}年级'.format(self.name,self.age,self.grade))
def speak1():
print('这是一个类方法')
s = student('jack',22,60,'大三')
s.speak()
student.speak1()
# 多重继承,逗号分隔
# 方法重写 直接重写不需要关键字
class privateTest:
__a = 0 #私有属性
#私有方法
def __privateMethod(self):
return '123'
def __init__(self, arg):
super(privateTest)
self.arg = arg
'''
类的专有方法:
__init__ : 构造函数,在生成对象时调用
__del__ : 析构函数,释放对象时使用
__repr__ : 打印,转换
__setitem__ : 按照索引赋值
__getitem__: 按照索引获取值
__len__: 获得长度
__cmp__: 比较运算
__call__: 函数调用
__add__: 加运算
__sub__: 减运算
__mul__: 乘运算
__div__: 除运算
__mod__: 求余运算
__pow__: 称方
'''
Python面向对象
最新推荐文章于 2022-05-29 16:43:35 发布