您的位置:首页 > 编程语言 > Python开发

python-魔法方法

2018-01-18 15:41 363 查看
一:__str__   __repr__

>>> class A():
def __str__(self): #用在被打印的时候需要用字符串的方式输出的时候,找到str的魔法方法来输出
return '打印某些东西'

>>> a = A()
>>> print(a)
打印某些东西
>>> a
<__main__.A object at 0x10559a2b0>
>>> class B():
def __repr__(self):
return '哈哈哈'

>>> b = B()
>>> b
哈哈哈
>>> print(b)
哈哈哈


1.1:内部方法可以用_开始,python赋值就是定义

import time as t

class MyTimer():
    def __init__(self):
        self.prompt = '倒计时未开始哦'
        self.lasted = []
        self.begin = 0
        self.end = 0
        
    

    def __str__(self):
        return self.prompt

    __repr__ = __str__

    
    #开始计时】
    def start(self):
        self.begin = t.localtime()
        print('即使开始000')

        

        #停止计时
    def stop(self):
        self.end = t.localtime()
        self._calc()
        print('计时结束!')

        #内部方法,计算运行时间
    def _calc(self):
        self.lasted = []
        self.prompt = '总共运行了'
        for index in range(6):
            self.lasted.append(self.end[index] - self.begin[index])
            self.prompt += str(self.lasted[index])

        print(self.prompt)
>>> t1 = MyTimer()
>>> t1
倒计时未开始哦
>>> t1.start()
即使开始000
>>> t1.stop()
总共运行了00001-55
计时结束!
>>>

1.2: setattr  getattr getattributte delattr

>>> class C:
def __getattribute__(self, name):
print('__getattribute__')
return super().__getattribute__(name)
def __getattr__(self, name):
print('__getattr__')
def __setattr__(self, name, value):
print('__setattr__')
super().__setattr__(name, value)
def __delattr__(self, name):
print('__delattr__')
super().__delattr__(name)

>>> c = C()
>>> c.x
__getattribute__
__getattr__
>>> c.x = 1
__setattr__
>>> c.x
__getattribute__
1
>>> del c.x
__delattr__
>>>



1.3:描述符:讲某种特殊类型的类的实例指派给领一个类的属性

1.4:容器类型的协议

如果定制的容器是不可变的:定义:__len__() 和 __getitem__()方法

如果定制的容器是可变的:定义:__len__()和__getitem__()方法,还需要定义__setitem__() 和__delitem__() 两个方法

不可变容器
class CoutList:
def __init__(self, *args):
self.values = [x for x in args]
self.count = {}.fromkeys(range(len(self.values)), 0)

def __len__(self):
return len(self, values)

def __getitem__(self, key):
self.count[key] += 1

return self.values[key]
>>> c1 = CoutList(1,3,5,7,9)
>>> c2 = CoutList(2,4,6,8,10)
>>> c1[1]
3
>>> c2[1]
4
&g
4000
t;>> c1[1] + c2[1]
7

>>> c1.count
{0: 0, 1: 2, 2: 0, 3: 0, 4: 0}
>>> c2[1]
4
>>> c2
<__main__.CoutList object at 0x104c96898>
>>> c2.count
{0: 0, 1: 3, 2: 0, 3: 0, 4: 0}
>>>
1.5:迭代 循环
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: