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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值