python __str__ ,__dict____str__ ,__unicode__
来源:互联网 发布:飞扬软件手游 编辑:程序博客网 时间:2024/05/23 00:14
python str ,dict____str ,unicode
使用版本:python 3+ 以后 ,删除了unicode 转而用 str 代替
说明:
1、str 是被 print 函数调用的,一般都是return一个什么东西。
2、这个东西应该是以字符串的形式表现的。如果不是要用str()函数转换。
3、当你打印一个类的时候,那么print首先调用的就是类里面的定义的str
classA(): def__init__(self): self.name='lee' self.age=18 self.job='it' def__str__(self): #重写 return 'xxx'a=A()print(A) #输出 <class '__main__.A'>print(a) #输出xxxprint(str(a)) #输出xxxprint(str(A)) #输出 <class '__main__.A'>print(A.__str__) #输出 <function A.__str__ at 0x00000000011C9510>print(a.__str__) #输出<bound method A.__str__ of <__main__.A object at 0x0000000000A49048>>
dict
一个对象的属性查找顺序遵循首先这里写代码片
查找实例对象自己,然后是类,接着是类的父类。
* __dict__是一个`这里写代码片`字典,键是属性名,值为属性值。* 实例有自己的__dict__,它对应的类也有自己的__dict__* 但是有些特殊的对象是没有__dict__属性的,这里不做讨论
classA(): def__init__(self): self.name='lee' self.age=18 self.job='it'a=A()print(a.__dict__) #输出 {'name': 'lee', 'job': 'it', 'age': 18}print(A.__dict__)'''输出类所有的 属性{'__init__': <function A.__init__ at 0x0000000000B3F9D8>,'__dict__': <attribute '__dict__' of 'A' objects>,'__weakref__': <attribute '__weakref__' of 'A' objects>,'__doc__': None, '__module__': '__main__'}'''
当打印 类 的dict属性时,列出了类所包含的属性,包括一些类内置属性和类变量及构造方法init
当打印 实例对象 的 dict 属性时,则打印 这个对象的 key ,value
字典转对象技巧
当我们有一个字典时,如
bokeyuan={“b”:1,
“o”:2,
“k”:3,
“e”:4,
“y”:5,
“u”:6,
“a”:7,
“n”:8,
}
现在想将其转换为一个对象,通常会这样写:
classDict2Obj: def__init__(self,bokeyuan): self.b = bokeyuan['b'] self.o = bokeyuan['o'] self.k = bokeyuan['k'] self.e = bokeyuan['e'] self.y = bokeyuan['y'] self.u = bokeyuan['u'] self.a = bokeyuan['a'] self.n = bokeyuan['n']
现在可以使用dict
class DicToObj(): def__init__(self,bokeyuan): self.__dict__.update(bokeyuan)
阅读全文
0 0
- python __str__ ,__dict____str__ ,__unicode__
- python __str__(self) __unicode__(self)
- Python __str__(self)和__unicode__(self)
- Python __str__(self)和__unicode__(self)
- Python __str__(self)和__unicode__(self)
- Python __str__(self)和__unicode__(self)
- Python中str()与__str__、repr()与__repr__、eval()、__unicode__的关系与区别
- python: 理解__str__
- python - __str__ 和 __repr__
- python 之 __str__
- python 之 __str__
- python: 理解__str__
- python __str__ , __repr__区别
- python - __str__ 和 __repr__
- python - __str__ 和 __repr__
- python - __str__ 和 __repr__
- [Python]Compare __repr__ & __str__
- python __str__()、__iter__()迭代器
- CSS,javascript简介
- Python 文件读取
- 2017 Rust 调查结果
- Android------第一次启动出现白屏或者黑屏
- Linux技术(1)--CentOS 6.5关闭防火墙步骤
- python __str__ ,__dict____str__ ,__unicode__
- 解决两个浮点数是否相等
- 大话设计模式——装饰者模式(总结)
- 常用的GDB命令
- java多线程基础介绍
- 如何查看已安装的CentOS版本信息
- Button按钮控件自绘操作
- 洛谷 P3383 筛素数 欧拉筛素数模板
- JP-Word简谱编辑下载 v4.95绿色完美版