Python学习之路(一)
程序员文章站
2024-02-25 09:40:52
...
- 判断是否是某种类型的实例: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学习之路(一)
-
百度地图js报错Uncaught TypeError: b.ga(...).nb is not a function 博客分类: js 乔乐共享众观千象每天进步一点点学习永无止境百度地图
-
百度地图js报错Uncaught TypeError: b.ga(...).nb is not a function 博客分类: js 乔乐共享众观千象每天进步一点点学习永无止境百度地图
-
深入浅出学习python装饰器
-
Python中shutil模块的学习笔记教程
-
Python编程实现数学运算求一元二次方程的实根算法示例
-
python 写入文件 博客分类: python python学习python写入文件写文件python写文件
-
python 写入文件 博客分类: python python学习python写入文件写文件python写文件
-
给Web前端初学者的一些建议和学习路线
-
Spring Boot学习入门之统一异常处理详解