码迷,mamicode.com
首页 > 编程语言 > 详细

Python随心记--类的内置attr属性

时间:2019-01-01 00:17:38      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:iter   +=   pass   dir   class   组合   mon   mat   import   

class Foo:
    x = 1
    def __init__(self,y):
        self.y = y
    def __getattr__(self, item):   #如果对象不存在的属性是会触发
        print(执行了__gerattr__)
    def __delattr__(self, item):   #删除的时候会触发
        print(执行了__delattr__)
        self.__dict__.pop(item)
    def __setattr__(self, key, value):   #设置属性是会触发,比如foo.x 当x不存在的时候就会触发__setattr__
        print(执行了__setattr__)
        #self.key = value   #不能致盲设置属性,会变成死循环(递归)
        self.__dict__[key] = value
foo = Foo(11)
print(dir(Foo))
组合的方式完成授权
import time
class FileHandle:
    def __init__(self,filename,mode=r,encoding=utf8):
        # self.filename = filename
        self.file = open(filename,mode,encoding=utf8)
        self.mode = mode
        self.encoding = encoding

    def write(self,line):
        t = time.strftime(%Y-%m-%d %T)
        return self.file.write(%s %s %(t,line))
    def __getattr__(self, item):
        # print(‘您请求的方法不存在‘)
        # self.file.read
        return getattr(self.file,item)   #返回self.file中的read方法

filehandle = FileHandle(a.txt,w+)
# print(filehandle.read)
filehandle.write(1111\n)
filehandle.write(2222\n)
filehandle.write(3333\n)

继承+派生完成包装
class List(list):
    def show_medllo(self):
        mid_index = int(len(self)/2);
        return self[mid_index]
    def append(self, p_object):
        if type(p_object) is str:
            # list.append(self,p_object)
            super().append(p_object)
        else:
           print(O(∩_∩)O,类型错了)
li = List(helloworld)


print(li.show_medllo())
li.append(720)
print(li)

issubclass() isinstance()
class Foo:
    pass
foo = Foo()
isinstance(foo,Foo)
issubclass(C,B)   #c类名雷曼B 判断c是否是继承B
__getattribute__
class Foo:
    def __init__(self,x):
        self.x = x
    def __getattr__(self, item):
        print(执行了__getattr__)
    def __getattribute__(self, item):   #属性有或者没有都出发她
        print(执行了__getattribute__)
        raise AttributeError(抛出异常了)
        # raise TabError(‘xxxxxxxxxxxxx‘)
foo = Foo(1)

foo.xxxx
item系列
class Foo:
    def __getitem__(self, item):
        print(getitem)
    def __setitem__(self, key, value):
        print(setitem)
    def __delitem__(self, key):
        print(delitem)

__str__ :自定义对象的显示方式
__repr__:自定义对象的显示方式

class Foo:
    def __str__(self):
        return 自定义对象的显示方式
    def __repr__(self):
        return 自定义对象的显示方式1

定制__format__
x = {0}{0}{0}.format(dog)
print(x)
format_dic={
    ymd:{0.year}{0.mon}{0.day},
    m-d-y:{0.mon}-{0.day}-{0.year},
    y:m:d:{0.year}:{0.mon}:{0.day}
}
class Date:
    def __init__(self,year,mon,day):
        self.year=year
        self.mon=mon
        self.day=day
    def __format__(self, format_spec):
        print(我执行啦)
        print(--->,format_spec)
        if not format_spec or format_spec not in format_dic:
            format_spec=ymd
        fm=format_dic[format_spec]
        return fm.format(self)
d1=Date(2016,12,26)
# format(d1) #d1.__format__()
# print(format(d1))
print(format(d1,ymd))
print(format(d1,y:m:d))
print(format(d1,m-d-y))
print(format(d1,m-d:y))
print(===========>,format(d1,asdfasdfsadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasd))
slots 属性 ,可节省内存(不推荐使用)
class Foo:
    __slots__ = [name,age]   #实例化的对象不再有__dict__方法

f = Foo()
f.name = lin
print(f.name)
__class__、__module__:查看对象来自那一模块

__del__:析构方法

__call__
class Foo:
    def __call__(self, *args, **kwargs):
        print(对象加小括号()也可以运行啦)
f = Foo()
f()
迭代器协议:

class Foo:
    def __init__(self,n):
        self.n = n
    def __iter__(self):   #加上后对象就可迭代 ,for循环
        pass

    def __next__(self):
        if self.n == 13:
            raise StopIteration(凉了)
        self.n += 1
        return self.n

f = Foo(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())

#斐那锲波
class Fib:
    def __init__(self):
        self._a = 1
        self._b = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self._a > 100:
            raise StopIteration(凉凉了)
        self._a,self._b = self._b,self._a + self._b

        return self._a

f = Fib()
print(next(f))
print(next(f))

for i in f:
    print(i)

 

 
 

Python随心记--类的内置attr属性

标签:iter   +=   pass   dir   class   组合   mon   mat   import   

原文地址:https://www.cnblogs.com/Essaycode/p/10203879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!