美文网首页
python面向对象之特殊方法

python面向对象之特殊方法

作者: 为瞬间停留 | 来源:发表于2018-04-17 20:44 被阅读14次

特殊方法的前后是有__,具体怎么用,直接看例子比较好。

1.python中 strrepr
如果要把一个类的实例变成 str,就需要实现特殊方法str():

class Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender
    def __str__(self):
        return '(Person: %s, %s)' % (self.name, self.gender)

现在,在交互式命令行下用 print 试试:

>>> p = Person('Bob', 'male')
>>> print p
(Person: Bob, male)

但是,如果直接敲变量 p:

>>> p
<main.Person object at 0x10c941890>

似乎str() 不会被调用。

因为 Python 定义了str()和repr()两种方法,str()用于显示给用户,而repr()用于显示给开发人员。

有一个偷懒的定义repr的方法:

class Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender
    def __str__(self):
        return '(Person: %s, %s)' % (self.name, self.gender)
    __repr__ = __str__

2.python中 cmp
对 int、str 等内置数据类型排序时,Python的 sorted() 按照默认的比较函数 cmp 排序,但是,如果对一组 Student 类的实例排序时,就必须提供我们自己的特殊方法 cmp():

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def __str__(self):
        return '(%s: %s)' % (self.name, self.score)
    __repr__ = __str__

    def __cmp__(self, s):
        if self.name < s.name:
            return -1
        elif self.name > s.name:
            return 1
        else:
            return 0
>>> L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77)]
>>> print sorted(L)
[(Alice: 77), (Bob: 88), (Tim: 99)]

需要先比较 score,在 score 相等的情况下,再比较 name。

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __str__(self):
        return '(%s: %s)' % (self.name, self.score)

    __repr__ = __str__

    def __cmp__(self, s):
        if self.score == s.score:
            return cmp(self.name, s.name)
        return -cmp(self.score, s.score)

L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
cmp( x, y )
参数
x -- 数值表达式。
y -- 数值表达式。
返回值
如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

3.python中 len
如果一个类表现得像一个list,要获取有多少个元素,就得用 len() 函数。

要让 len() 函数工作正常,类必须提供一个特殊方法len(),它返回元素的个数。

例如,我们写一个 Students 类,把名字传进去:

class Students(object):
    def __init__(self, *args):
        self.names = args
    def __len__(self):
        return len(self.names)

只要正确实现了len()方法,就可以用len()函数返回Students实例的“长度”:

>>> ss = Students('Bob', 'Alice', 'Tim')
>>> print len(ss)
3

4.python中数学运算

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

class Rational(object):
    def __init__(self, p, q):
        self.p = p
        self.q = q
    def __add__(self, r):
        return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
    def __sub__(self, r):
        return Rational(self.p * r.q - self.q * r.p, self.q * r.q)
    def __mul__(self, r):
        return Rational(self.p * r.p, self.q * r.q)
    def __div__(self, r):
        return Rational(self.p * r.q, self.q * r.p)
    def __str__(self):
        g = gcd(self.p, self.q)
        return '%s/%s' % (self.p / g, self.q / g)
    __repr__ = __str__

r1 = Rational(1, 2)
r2 = Rational(1, 4)
print r1 + r2
print r1 - r2
print r1 * r2
print r1 / r2

5.结果转换
Rational类实现了有理数运算,但是,如果要把结果转为 int 或 float 怎么办?
如果要把 Rational 转为 int,应该使用:

r = Rational(12, 5)
n = int(r)

要让int()函数正常工作,只需要实现特殊方法int():

class Rational(object):
    def __init__(self, p, q):
        self.p = p
        self.q = q
    def __int__(self):
        return self.p // self.q
>>> print int(Rational(7, 2))
3
>>> print int(Rational(1, 3))
0

6.python中 @property
python中 @property
考察 Student 类:

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

当我们想要修改一个 Student 的 scroe 属性时,可以这么写:

s = Student('Bob', 59)
s.score = 60
但是也可以这么写:

s.score = 1000
显然,直接给属性赋值无法检查分数的有效性。

如果利用两个方法:

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score
    def get_score(self):
        return self.__score
    def set_score(self, score):
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self.__score = score

这样一来,s.set_score(1000) 就会报错。

这种使用 get/set 方法来封装对一个属性的访问在许多面向对象编程的语言中都很常见。

但是写 s.get_score() 和 s.set_score() 没有直接写 s.score 来得直接。

有没有两全其美的方法?----有。

因为Python支持高阶函数,在函数式编程中我们介绍了装饰器函数,可以用装饰器函数把 get/set 方法“装饰”成属性调用:

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score
    @property
    def score(self):
        return self.__score
    @score.setter
    def score(self, score):
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self.__score = score

注意: 第一个score(self)是get方法,用@property装饰,第二个score(self, score)是set方法,用@score.setter装饰,@score.setter是前一个@property装饰后的副产品。

现在,就可以像使用属性一样设置score了:

>>> s = Student('Bob', 59)
>>> s.score = 60
>>> print s.score
60
>>> s.score = 1000
Traceback (most recent call last):
  ...
ValueError: invalid score
说明对 score 赋值实际调用的是 set方法。

7.python中 slots
由于Python是动态语言,任何实例在运行期都可以动态地添加属性。

如果要限制添加的属性,例如,Student类只允许添加 name、gender和score 这3个属性,就可以利用Python的一个特殊的slots来实现。

顾名思义,slots是指一个类允许的属性列表:

class Student(object):
    __slots__ = ('name', 'gender', 'score')
    def __init__(self, name, gender, score):
        self.name = name
        self.gender = gender
        self.score = score
现在,对实例进行操作:
>>> s = Student('Bob', 'male', 59)
>>> s.name = 'Tim' # OK
>>> s.score = 99 # OK
>>> s.grade = 'A'
Traceback (most recent call last):
  ...
AttributeError: 'Student' object has no attribute 'grade'

slots的目的是限制当前类所能拥有的属性,如果不需要添加任意动态的属性,使用slots也能节省内存。

8.python中 call

在Python中,函数其实是一个对象:

>>> f = abs
>>> f.__name__
'abs'
>>> f(-123)
123

由于 f 可以被调用,所以,f 被称为可调用对象。

所有的函数都是可调用对象。

一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法call()。

我们把 Person 类变成一个可调用对象:

class Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

    def __call__(self, friend):
        print 'My name is %s...' % self.name
        print 'My friend is %s...' % friend
现在可以对 Person 实例直接调用:

>>> p = Person('Bob', 'male')
>>> p('Tim')
My name is Bob...
My friend is Tim...

单看 p('Tim') 你无法确定 p 是一个函数还是一个类实例,所以,在Python中,函数也是对象,对象和函数的区别并不显著。

相关文章

  • python面向对象之特殊方法

    特殊方法的前后是有__,具体怎么用,直接看例子比较好。 1.python中 str和repr如果要把一个类的实例变...

  • 营销比赛二三事

    Python面向对象编程三大特性调研 Python面向对象之封装 在Python中,没有类似 private 之类...

  • Python学习笔记5

    面向对象 类和对象的创建 属相相关 方法相关 元类 内置的特殊属性 内置的特殊方法 面向对象 类和对象的创建 类 ...

  • python面向对象之相关函数和特殊方法

    与类有关的几个函数 类的特殊方法 类属性__dict__ # 类的属性(包含一个字典,由类的数据属性组成)__...

  • Python学习-面向对象

    查看所有Python相关学习笔记 面向对象 面向对象知识点汇总: 面向对象静态属性实例属性(self)静态方法(@...

  • 2018-03-23

    python 链接 mysql 普通连接方法 面向对象连接方法

  • python面向对象编程(3)|方法和访问权限

    今天我们来学习python面向对象编程的三种方法和访问权限。 方法 上次我们已经说过,python面向对象编程一共...

  • python面向对象学习笔记-01

    学习笔记 # 0,OOP-Python面向对象 - Python的面向对象 - 面向对象编程 - 基础 -...

  • Python面向对象之魔术方法

    str改变对象的字符串显示。可以理解为使用print函数打印一个对象时,会自动调用对象的str方法 定义对象的字符...

  • Python 面向对象编程

    Python 面向对象编程(一) Python 面向对象编程(一) 虽然Python是解释性语言,但是它是面向对象...

网友评论

      本文标题:python面向对象之特殊方法

      本文链接:https://www.haomeiwen.com/subject/mgeohftx.html