目录:

1、不一样的列表

2、改变type中的规则,创建类:类属性大写

3、%s字串格式化,不用元组用字典

4、没有参数抛出异常

5、字符串签名加f 格式化字符串

6、attr库

7、python的十大装B操作


1、不一样的列表

list1 = ["a", "b", "c"]
self, *args = list1
print(self)
print(args)

输出:

a
['b', 'c']

  

2、改变type中的规则,创建类:类属性大写

class UpperAttrMetaClass(type):
def __new__(cls, class_name, class_parents, class_attrs):
# 遍历属性字典,把不是__开头的属性名字变为大写
newAttr = {}
for k, v in class_attrs.items():
if not k.startswith("__"):
newAttr[k.upper()] = v # 方法1:通过‘type’来创建类对象
# return type(class_name, class_parents, newAttr) # 方法2:复用type.__new__方法创建类对象
# return type.__new__(cls, class_name, class_parents, newAttr) # 方法3:使用super方法创建类对象
return super(UpperAttrMetaClass, cls).__new__(cls, class_name, class_parents, newAttr) # python3的用法
class Foo(object, metaclass=UpperAttrMetaClass):
bar = "bip" # 判断Foo类中是否有某个属性
print(hasattr(Foo, 'bar'))
print(hasattr(Foo, "BAR")) f = Foo()
print(f.BAR)

输出:

False
True
bip

  

3、%s字串格式化,不用元组用字典

str= """
第一个:%(delim)s
第二个:%(id)s
"""
str_new = str % {'delim': "$", 'id': 9}
print(str_new)

输出:

第一个:$
第二个:9

  

4、没有参数抛出异常

def func1(*args, **kwargs):
if not args: # 无参数报错
raise TypeError("descriptor 'format' of 'Formatter' object needs an argument")
else:
n_args = len(args)
pattern = " ".join("%s," for x in range(n_args))
# print(pattern)
return "I am func1, my args is: " + pattern % args if __name__ == '__main__':
# 有参数正常
res1 = func1("a1", "a2", "a3")
print(res1) # 无参数报错
res2 = func1()
print(res2)

  

输出:

I am func1, my args is: a1, a2, a3,

Traceback (most recent call last):
File "D:/aaa-py/tmp/my00-tool.py", line 17, in <module>
res2 = func1()
File "D:/aaa-py/tmp/my00-tool.py", line 3, in func1
raise TypeError("descriptor 'format' of 'Formatter' object needs an argument")
TypeError: descriptor 'format' of 'Formatter' object needs an argument

  

5、字符串签名加f 格式化字符串

例子:

https://blog.csdn.net/sunxb10/article/details/81036693

 

6、attr库

https://www.attrs.org/en/latest/glossary.html 

7、python的十大装B操作

https://blog.csdn.net/xufive/article/details/102856921

  

最新文章

  1. WCF初探文章列表
  2. web.py学习心得
  3. vim符号列表窗口
  4. mysqli_multi_query($link, $sql_w);
  5. Java性能优化权威指南-读书笔记(四)-JVM性能调优-延迟
  6. 12.iscsi-target
  7. iPhone不同机型适配 6/6plus --备用
  8. ASP.NET 资料下载
  9. More lumber is required
  10. SQL 查询时间段内的时间
  11. VirtulBox虚拟机搭建Linux Centos系统
  12. Android平台根目录文件
  13. Cesium3DTileset示例
  14. Java 枚举(enum) 详解7种常见的用法
  15. [转]kindeditor隐藏上传图片框网络图片或本地上传的功能
  16. DateTimeOffset DateTime
  17. LeetCode——3. Longest Substring Without Repeating Characters
  18. Python glob.md
  19. jsp渲染
  20. git cherry-pick基本使用

热门文章

  1. 学习PHP垃圾回收机制了解引用计数器的概念
  2. C#string数组转换到int数组并得到最大最小值
  3. 简单好用的包管理器 brew
  4. CSS浮动与清除浮动(overflow)例子
  5. 【UVa】Partitioning by Palindromes(dp)
  6. jquery设置cors跨域
  7. C语言若干知识点归记
  8. linux 远端执行shell脚本 批量结束各个远端节点进程
  9. [转]C# 超高速高性能写日志 代码开源
  10. 时序数据库技术体系 – InfluxDB TSM存储引擎之TSMFile