面向对象进阶

#
210512_
面向对象进阶
class Rectangle:
#
新建一个长方形的类
def __init__(self,length,width):
#
初始化方法
self.length=length
self.width=width
def perimeter(self):
#
实例方法
return
(self.length+self.width)*2
def area(self):
#
实例方法
return
self.length*self.width
@classmethod
#
装饰器
,
声明下面的方法是类方法
def features(cls):
print('两边的长相等,两边的宽也相等,长和宽的角度为90°')
@staticmethod
#
声明下面的方法是静态方法
def sumdata():
#
静态方法其实就是一个普通的函数
,
和类没有直接联系
,
只是写在了类里面
return
'
HelloWord'
rec=Rectangle(6,4)
#
实例化一个长方形
#
print(rec.perimeter())
#
实例方法
,
只能由实例调用
#
print(rec.area())
#
Rectangle.features()
#
类方法
,
可以由类调用
,
也可以由实例调用
#
rec.features()
#
print(Rectangle.sumdata())
#
静态方法
,
既可以由类调用
,
也可以由实例调用
#
print(rec.sumdata())
#
判断一个对象是方法还是函数
,
可以用
type
function
表示函数
,
method
表示方法
#
print(type(rec.perimeter))
#
实例方法就是方法
#
print(type(rec.features))
#
类方法是方法
#
print(type(rec.sumdata))
#
静态方法是函数
#
也可以使用
i
nspect
模块进行判断
,
i
nspect
判断某个对象是否属于某个类
,
返回值是布尔型
import
inspect
#
print(inspect.ismethod(Rectangle.features))
#True
#
print(inspect.ismethod(Rectangle.sumdata))
#False
#
print(inspect.isfunction(Rectangle.features))
#
print(inspect.isfunction(Rectangle.sumdata))
#
类的继承
#1.
完全继承
#
class Square(Rectangle):
#
pass
#
squ=Square(6,6)
#
print(squ.perimeter())
#
print(squ.area())
#2.
部分继承
,
修改初始化方法
,
用户只需要输入一个边长
#
class Square(Rectangle):
#
def __init__(self,side):
#
self.length=side
#
self.width=side
#
squ=Square(6)
#
print(squ.perimeter())
#
print(squ.area())
#3.
全部重写
,
相当于没有继承
#
class Square(Rectangle):
#
def __init__(self,side):
#
self.side=side
#
self.side=side
#
def perimeter(self):
#
return self.side*4
#
def area(self):
#
return self.side**2
#
squ=Square(6)
#
print(squ.perimeter())
#
print(squ.area())
#
继承父类方法的同时
,
对父类的方法进行扩展
class Square(Rectangle):
def __init__(self,side):
self.length=side
self.width=side
@classmethod
def features(cls):
super()
.
features()
#
声明继承父类的方法
print('长和宽也相等')
@property
#
声明下面的方法作为一个属性而不是方法
def fun1(self):
return 'HelloWorld'
#
squ=Square(6)
#
squ.features()
#
print(squ.fun1)
世界上最美的风景,是自己努力的模样
原文地址:https://www.cnblogs.com/xiong-hua/p/14778984.html