美文网首页
Python学习之路(一)

Python学习之路(一)

作者: stone呀 | 来源:发表于2018-01-22 17:57 被阅读11次
  • 判断是否是某种类型的实例:isinstance()方法
  • 可以用 type() 函数获取变量的类型,它返回一个 Type 对象
>>> type(123)
<type 'int'>
>>> s = Student('Bob', 'Male', 88)
>>> type(s)
<class '__main__.Student'>
  • 可以用 dir() 函数获取变量的所有属性
>>> dir(123)   # 整数也有很多属性...
['__abs__', '__add__', '__and__', '__class__', '__cmp__', ...]
  • getattr() 和 setattr( )函数
>>> s = Student('Bob', 'Male', 88)
>>> getattr(s, 'name')  # 获取name属性
'Bob'

>>> setattr(s, 'name', 'Adam')  # 设置新的name属性

>>> s.name
'Adam'

>>> getattr(s, 'age')  # 获取age属性,但是属性不存在,报错:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'age'

>>> getattr(s, 'age', 20)  # 获取age属性,如果属性不存在,就返回默认值20:
20

相关文章

网友评论

      本文标题:Python学习之路(一)

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