流程的Python 第九章:符合Python风格的对象

前言:
自己定义类,让类的行为跟真正的Python对象一样。

目录:

  1. 内容回顾
  2. 相关资料
  3. 阅读后感

正文:
一. 内容回顾
1.1 对象表现形式
repr() :
以便于开发者理解的方式返回对象的字符串表示形式
str() :
以便于用户理解的方式返回对象的字符串表示形式

1.2 再谈向量类

# -*- coding:utf-8 -*-
import math


class MyVector:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def __iter__(self):
        return (i for i in (self.x, self.y))

    def __repr__(self):
        class_name = type(self).__name__
        return '{}({!r}, {!r})'.format(class_name, *self)

    def __str__(self):
        return str(tuple(self))

    def __abs__(self):
        return math.hypot(self.x, self.y)


if __name__ == '__main__':
    v1 = MyVector(3, 4)
    print v1.x, v1.y
    x, y = v1
    print x, y
    print v1
    print abs(v1)

输出结果:

/usr/bin/python /Users/jenkins/Desktop/Timen/Python/FluentPython/chapter_09/Vector.py
3.0 4.0
3.0 4.0
(3.0, 4.0)
5.0

Process finished with exit code 0

1.3 备选构造方法

1.4 classmethod与staticmethod

# -*- coding:utf-8 -*-


class MyDemo:
    @classmethod
    def myClassMethod(*args):
        return args

    @staticmethod
    def myStaticMethod(*args):
        return args


if __name__ == '__main__':
    print MyDemo.myClassMethod()
    print MyDemo.myClassMethod("Test Class")
    print MyDemo.myStaticMethod()
    print MyDemo.myStaticMethod("Test Static")

输出结果:

/usr/bin/python /Users/jenkins/Desktop/Timen/Python/FluentPython/chapter_09/MyClassmethod.py
(<class __main__.MyDemo at 0x10ac6e870>,)
(<class __main__.MyDemo at 0x10ac6e870>, 'Test Class')
()
('Test Static',)

Process finished with exit code 0

class method装饰器非常有用,但是我从未见过不得不用static method的情况。(摘自原文)

1.5 格式化显示
内置的format()函数和str.format()

1.6 可散列的vector2d

1.7 Python的私有属性和“受保护的”属性

1.8 使用_ slots _ 类属性节省空间
_ slots _属性节省内存,但是slots属性有点棘手,因此仅当处理特别多的实例(数百万个,而不是几千个)时才建议使用。

1.9 覆盖类属性

二. 相关资料
2.1 编写的类的行为向Python对象看齐:

class Vector():

    def __init__(self,x,y):

        self.x=float(x)

        self.y=float(y)

    def __iter__(self):

        return (i for i in (self.x,self.y))

    def __str__(self):

        return str(tuple(self))

    def __bytes__(self):

        return (bytes([ord(self.typecode)])+bytes(array(self.typecode,self)))

    def __eq__(self, other):

        return tuple(self) == tuple(other)

    def __abs__(self):

        return math.hypot(self.x,self.y)

    def __bool__(self):

        return bool(abs(self))

if __name__== "__main__":

    v1=Vector(3,4)

    v2=Vector(3,1)

    x,y=v1          #调用__iter__

    print x,y

    print abs(v1)   #调用__abs__

    print v1==v2    #调用__eq__

    print bool(v1)  #调用__bool__

    print bytes(v1) #调用__bytes__

2.2 class method的使用

class Date_format(object):

    def __init__(self,day=0,month=0,year=0):

        self.day=day

        self.month=month

        self.year=year

    @classmethod

    def from_string(cls,date_string):

        day,month,year=map(int,date_string.split('-'))

        date=cls(day,month,year)

        return date



if __name__== "__main__":

    d=Date_format.from_string('2017-7-10')

    print d.day,d.month,d.year

通过from_string来得到具体的日期并通过date=cls(day,month,year)来实例化对象并返回这个实例化对象

2.3 _ slots _ 笔记:
_ slots _用元组的形式保存变量,而非字典。且slots无法添加变量。由于采用了元组的方式,因此在创建多个实例的时候,会节省不少内存。但由于无法添加变量,也有很大的局限性。最适合slots的场景就是类的变量恒定不变且会创建多个实例化对象的时候,可以采用slots

三. 阅读后感
符合Python风格的对象指的是编写的类型的成员方法更多的使用Python内置函数重写,列如:_ abs _成员函数,当类的实列对象的行为abs(object)即可。

参考:
1. 创建一个符合Python风格的对象(1)
2. 创建一个符合Python风格的对象(2)
3. 流畅python学习笔记:第九章:符合python风格的对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值