Python:Python学习总结(三)

作者: 码市冲冲冲 | 来源:发表于2021-03-29 21:09 被阅读0次

魔法方法

对象构造相关:newinitdel

1 from os.path import join
2 
3 class FileObject:
4     '''Wrapper for file objects to make sure the file gets closed on deletion.'''
5 
6     def __init__(self, filepath='~', filename='sample.txt'):
7         # open a file filename in filepath in read and write mode
8         self.file = open(join(filepath, filename), 'r+')
9 
10     def __del__(self):
11         self.file.close()
12         del self.file

运算符重载:所有运算符都能重载。

1 class Word(str):
2     '''Class for words, defining comparison based on word length.'''
3 
4     def __new__(cls, word):
5         # Note that we have to use __new__. This is because str is an immutable
6         # type, so we have to initialize it early (at creation)
7         if ' ' in word:
8             print "Value contains spaces. Truncating to first space."
9             word = word[:word.index(' ')] # Word is now all chars before first space
10         return str.__new__(cls, word)
11 
12     def __gt__(self, other):
13         return len(self) > len(other)
14 
15     def __lt__(self, other):
16         return len(self) < len(other)
17 
18     def __ge__(self, other):
19         return len(self) >= len(other)
20 
21     def __le__(self, other):
22         return len(self) <= len(other)
23 
24 print(Word("duan") > Word("wei"))

属性访问

1 class AccessCounter:
2     '''A class that contains a value and implements an access counter.
3     The counter increments each time the value is changed.'''
4 
5     def __init__(self, value):
6         super(AccessCounter, self).__setattr__('counter', 0)
7         super(AccessCounter, self).__setattr__('value', value)
8 
9     def __setattr__(self, name, value):
10         if name == 'value':
11             super(AccessCounter, self).__setattr__('counter', self.counter + 1)
12         # Make this unconditional.
13         # If you want to prevent other attributes to be set, raise AttributeError(name)
14         super(AccessCounter, self).__setattr__(name, value)
15 
16     def __delattr__(self, name):
17         if name == 'value':
18             super(AccessCounter, self).__setattr__('counter', self.counter + 1)
19         super(AccessCounter, self).__delattr__(name)

集合实现

1 class FunctionalList:
2     '''A class wrapping a list with some extra functional magic, like head,
3     tail, init, last, drop, and take.'''
4 
5     def __init__(self, values=None):
6         if values is None:
7             self.values = []
8         else:
9             self.values = values
10 
11     def __len__(self):
12         return len(self.values)
13 
14     def __getitem__(self, key):
15         # if key is of invalid type or value, the list values will raise the error
16         return self.values[key]
17 
18     def __setitem__(self, key, value):
19         self.values[key] = value
20 
21     def __delitem__(self, key):
22         del self.values[key]
23 
24     def __iter__(self):
25         return iter(self.values)
26 
27     def __reversed__(self):
28         return FunctionalList(reversed(self.values))
29 
30     def append(self, value):
31         self.values.append(value)
32     def head(self):
33         # get the first element
34         return self.values[0]
35     def tail(self):
36         # get all elements after the first
37         return self.values[1:]
38     def init(self):
39         # get elements up to the last
40         return self.values[:-1]
41     def last(self):
42         # get last element
43         return self.values[-1]
44     def drop(self, n):
45         # get all elements except first n
46         return self.values[n:]
47     def take(self, n):
48         # get first n elements
49         return self.values[:n]

可调用对象,像方法一样调用对象

1 class Entity:
2     '''Class to represent an entity. Callable to update the entity's position.'''
3 
4     def __init__(self, size, x, y):
5         self.x, self.y = x, y
6         self.size = size
7 
8     def __call__(self, x, y):
9         '''Change the position of the entity.'''
10         self.x, self.y = x, y
11         print(x, y)
12 
13 entity = Entity(5, 1, 1)
14 entity(2, 2)

资源管理

1 class Closer:
 2     def __enter__(self):
 3         return self
 4 
 5     def __exit__(self, exception_type, exception_val, trace):
 6         print("清理完成")
 7         return True;
 8 
 9 with Closer() as closer:
10     pass

对象描述符

1 class Meter(object):
2     '''Descriptor for a meter.'''
3 
4     def __init__(self, value=0.0):
5         self.value = float(value)
6     def __get__(self, instance, owner):
7         return self.value
8     def __set__(self, instance, value):
9         self.value = float(value)
10 
11 class Foot(object):
12     '''Descriptor for a foot.'''
13 
14     def __get__(self, instance, owner):
15         return instance.meter * 3.2808
16     def __set__(self, instance, value):
17         instance.meter = float(value) / 3.2808
18 
19 class Distance(object):
20     '''Class to represent distance holding two descriptors for feet and
21     meters.'''
22     meter = Meter()
23     foot = Foot()

Mixin(也叫掺入)

掺入模块:playable.py

1 # coding=utf-8
2 
3 def paly(self):
4     print("游戏中...")

掺入目标模块:test.py

1 #coding:utf-8
2 
3 class TestClass:
4     def method1(self):
5         print("方法1")
6 
7 def method2(self):
8     print("方法2")
9 
10 TestClass.method2 = method2
11 
12 test = TestClass()
13 test.method1() # 方法1
14 test.method2() # 方法2

Meta Programming(元编程)

1 TestClass = type("TestClass", (object,), {
2     "say": lambda self : print("你好啊")
3 })
4 
5 test = TestClass()
6 test.say()
1 def getter(name):
2     def getterMethod(self):
3         return self.__getattribute__(name)
4     return getterMethod
5 
6 def setter(name):
7     def setterMethod(self, value):
8         self.__setattr__(name, value)
9     return setterMethod    
10 
11 class TestClass:
12     getName = getter("name")
13     setName = setter("name")
14 
15 test = TestClass()
16 test.setName("石浩阳")
17 print(test.getName())

相关文章

  • Python:Python学习总结(三)

    魔法方法 对象构造相关:new、init、del。 运算符重载:所有运算符都能重载。 属性访问 集合实现 可调用对...

  • 2017.6.13-14

    学习python总结python常用的方法string的常用方法dictionary的常用方法 python抽象,...

  • 资料

    Python爬虫系列(一)初期学习爬虫的拾遗与总结(11.4更) Python爬虫学习系列教程 Python爬虫学习手册

  • 使用python机器学习(四)

    前面三篇文章《使用python机器学习(一)》、《使用python机器学习(二)》、《使用python机器学习(三...

  • 2018-03-10

    Python第二周学习总结 导读:这是python学习的第二周,在第二周,学习了大量的python基础,其中有字符...

  • Python爬虫学习(十六)初窥Scrapy

    Python爬虫学习(一)概述Python爬虫学习(二)urllib基础使用Python爬虫学习(三)urllib...

  • python学习 三 03 再爬一个网站,根据分页,下载图片

    python学习 三 03 再爬一个网站,根据分页,下载图片 Python安装 python学习 一 python...

  • Python学习总结【连载】(三)

    Python学习总结【连载】(三) 2018.06.14 Juttachen 概述 + 10 数据类型转换 + 1...

  • python学习总结

    关于Python的一些总结 希望自己以后在学习Python的过程中可以边学习边总结,就自己之前的学习先做以总结,之...

  • python-扬帆启程

    Python学习 - 新的启程 前言 闲着无聊,重学python,记录总结。 Life is short,I us...

网友评论

    本文标题:Python:Python学习总结(三)

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