Python – 面向对象编程
1、一切皆对象
2、扩展性好
在允许修改原函数内容的前提下,类方法对于参数列表的更新(只需在实例化时添加需要更新的参数)会比公共方法(扩展参数列表)的参数列表的改动更小,尤其是当新增参数已经在类的属性中了
公共方法需要新增信息时,例如新增(d、e、f、g),会对公共函数的形参列表造成巨大的冲击;若使用类方法,只需在属性中添加几个字段(仅会波及到类实例化的形参列表),便可直接在函数体中进行修改,不会波及原有的形参列表
3、实例
在实际的开发中,往往会遇到不同的主体在功能或属性上具有某种相似性,面向对象编程的方式在面对这种功能扩展的时候,具有很大的优势,即面向对象编程具有良好的扩展性
存在父子级关系或并列关系的类时,设计一个基类。例如一种数据模型系统:定义各种各样的数据结构,但是对于某些特定的属性,对赋给它们的值添加一些强制限制
# 基类,使用描述符来设置值
class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr(self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
# Descriptor for enforcing types
class Typed(Descriptor):
expected_type = type(None)
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('expected' + str(self.expected_type))
super().__set__(instance, value)
# Descriptor for enforcing values
class Unsigned(Descriptor):
def __set__(self, instance, value):
if value < 0:
raise ValueError('Expected >= 0')
super().__set__(instance, value)
class MaxSized(Descriptor):
def __init__(self, name=None, **opts):
if 'size' not in opts:
raise TypeError('missing size option')
super().__init__(name, **opts)
def __set__(self, instance, value):
if len(value) >= self.size:
raise ValueError('size must be < ' + str(self.size))
super().__set__(instance, value)
# 以上类是构建一个数据系统
# 以下实现不同的数据类型
class Integer(Typed):
expected_type = int
class UnsignedInteger(Integer, Unsigned):
pass
class Float(Typed):
expected_type = float
class UnsignedFloat(Float, Unsigned):
pass
class String(Typed):
expected_type = str
class SizedString(String, MaxSized):
pass
# 有了以上数据对象,就可以定义类了
class Stock:
# Specify constraints
name = SizedString('name', size=8)
shares = UnsignedInteger('shares')
price = UnsignedFloat('price')
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
if __name__ == '__main__':
stock = Stock('ACM', 50, 91.1)
print(stock.name, stock.shares, stock.price)
stock.price = '50'
版权声明:本文为balalabiu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。