python数据类型-1
一.说明
学习一门语言,最后能走多远,在我看来就是基础有多扎实,python中的数据类型无疑就是基础中的基础,让我们开始今天的日拱一卒!python 数据类型。
二.检查对象的类型、属性、方法(Python 的自省机制)
1.获取对象类型
#type()
x = 42
print(type(x)) # <class 'int'>
2.检查对象的属性和方法
class MyCar:
__slots__ = ('name','color')
def __init__(self,name,color):
self.name = name
self.color = color
def run(self):
print(f'{self.name}:在跑')
_bm = MyCar('宝马','金色')
print(dir(_bm)) # 包含 MyCar 和其他属性
'''
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'color', 'name', 'run']
'''
3.获取对象的文档字符串:使用 help()
函数可以查看对象的文档信息。
class MyCar:
'''
这是python中一个类的定义
'''
__slots__ = ('name','color')
def __init__(self,name,color):
self.name = name
self.color = color
def run(self):
print(f'{self.name}:在跑')
_bm = MyCar('宝马','金色')
print(help(_bm))
'''
Help on MyCar in module __main__ object:
class MyCar(builtins.object)
| 这是python中一个类的定义
|
| Methods defined here:
|
| __init__(self, name, color)
| Initialize self. See help(type(self)) for accurate signature.
|
| run(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| color
|
| name
'''
4.检查类型 可以使用 isinstance()
检查一个对象是否是某个特定类的实例。
print(isinstance(x, int)) # True
注意:python中 is和isinstance有什么区别?
is
用于判断两个对象是否是同一个对象(即它们的内存地址是否相同)
a = [1, 2, 3]
b = a
c = a[:]
print(a is b) #True
print(a is c) #False
5.获取属性的值和方法:使用 getattr()
和 setattr()
可以动态获取和设置对象的属性
class MyCar:
def __init__(self,name,color):
self.name = name
self.color = color
def run(self):
print(f'{self.name}:在跑')
_bm = MyCar('宝马','金色')
setattr(_bm, 'price', 100)
print(_bm.price) #100
print(getattr(_bm, 'price')) #100
6.检测对拥有属性:hasattr()
class MyCar:
__slots__ = ('name','color')
def __init__(self,name,color):
self.name = name
self.color = color
def run(self):
print(f'{self.name}:在跑')
_bm = MyCar('宝马','金色')
print(hasattr(_bm,'price')) #False
print(hasattr(_bm,'color')) #True
#hasattr 用于检查对象的属性,不适用于检查类本身的实例属性。
print(hasattr(MyCar,'price')) #False
print(MyCar.__slots__) #('name', 'color')
三.数据类型
- Number:整数(int)浮点数(float)复数(complex)
- String:字符串
- bool:布尔类型
- None:表示没有值或空值,只有一个值
None
- list、tuple、range:序列类型
- dict:字典 映射类型
- set、frozenset:集合类型
- class:自定义类型
1-4为基础类型,5-7为容器类型 8为自定义类型
1.Number
a = 1
b = 2
c = 1.233
print(a+b)#3
这里需要思考的是python中不同于其他语言中int32 int64 float32 float64这些区别只有 int 和float?
那么为什么呢?
或者说为什么其他语言要把类型分的这么细?
其他语言说白了就是为了性能考虑对这些进行切片,这样对资源管控更好;
但python没有 这样更符合人的使用习惯,但是降低了性能 。
随着我们对编程的理解越来越多 会发现不仅仅是编程有切片现实中也处处可见切片,比如电脑CPU
一级、二级、三级缓存。。
Number常用的方法:
import math
# 数值转换
x = 3.14
y = int(x) # 转换为整数
print(y) # 3
# 数学运算
print(abs(-10)) # 10
print(pow(2, 3)) # 8
print(round(3.14159, 2)) # 3.14
# 使用 math 模块
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
print(math.sqrt(16)) # 4.0
print(math.log(100, 10)) # 2.0
2.字符串(str)
在python中可以使用 '' "" ''''''来标识字符串
a = 'Hello World!'
b = "Hello World!"
c ='''
Note that Python 3.6.8
cannot be used on Windows XP or earlier.
'''
d = '''
Note that Python 3.6.8 .
cannot be used on Windows\n XP or earlier.
'''
e = '''
Note that Python 3.6.8 .
cannot be used on Windows\\n XP or earlier.
'''
f = R'''
Note that Python 3.6.8 .
cannot be used on Windows\t XP or earlier.
'''
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(chr(65))
这里隐藏二个概念:
转义字符:\t 和 \n还有\都是转义字符
取消转义:字符串前加r或者R
常用的转义字符:
换行:\n
- 表示换行。
制表符:\t
- 表示水平制表符(tab)。
反斜杠:\\
- 表示反斜杠字符本身。
单引号:\'
- 在单引号字符串中表示单引号。
双引号:\"
- 在双引号字符串中表示双引号。
回车:\r
- 表示回车符。
退格:\b
- 表示退格符。
退格:\f
- 表示换页符。
八进制值:\ooo
- 表示八进制值。
十六进制值:\xhh
- 表示十六进制值
字符串常用的方法:
# 1. 大小写转换
# str.upper():将字符串转换为大写。
# str.lower():将字符串转换为小写。
# str.title():将每个单词的首字母大写。
# str.capitalize():将第一个字母大写,其他字母小写。
# str.swapcase():将大写字母转换为小写,小写字母转换为大写。
# 2. 去除空白
# str.strip():去除字符串两端的空白字符。
# str.lstrip():去除字符串左侧的空白字符。
# str.rstrip():去除字符串右侧的空白字符。
# 3. 查找和替换
# str.find(sub):查找子字符串,返回第一个索引,如果未找到返回 -1。
# str.index(sub):查找子字符串,返回第一个索引,如果未找到引发 ValueError。
# str.replace(old, new):替换字符串中的子字符串。
# 4. 分割和连接
# str.split(sep):将字符串按指定分隔符分割为列表。
# str.join(iterable):将可迭代对象中的字符串连接为一个字符串。
# 5. 检查字符串内容
# str.startswith(prefix):检查字符串是否以指定前缀开头。
# str.endswith(suffix):检查字符串是否以指定后缀结尾。
# str.isalpha():检查字符串是否只包含字母。
# str.isdigit():检查字符串是否只包含数字。
# str.isalnum():检查字符串是否只包含字母和数字。
# str.isspace():检查字符串是否只包含空白字符。
# 6. 格式化字符串
# str.format():格式化字符串。
# str.format_map():使用字典格式化字符串。
# 7. 其他方法
# str.splitlines():按行分割字符串。
# str.count(sub):计算子字符串出现的次数。
# str.capitalize():将字符串的第一个字符转换为大写。
######################################################
s = " hello, World! "
# 大小写转换
print(s.upper()) # " HELLO, WORLD! "
print(s.lower()) # " hello, world! "
print(s.title()) # " Hello, World! "
print(s.strip()) # "hello, World!"
# 查找和替换
print(s.find("World")) # 8
print(s.replace("World", "Python")) # " hello, Python! "
# 分割和连接
words = s.split(", ")
print(words) # [' hello', 'World! ']
print(" - ".join(words)) # " hello - World! "
# 检查内容
print(s.startswith(" hello")) # True
print(s.isalpha()) # False
3.布尔型(bool)
只有两个值:True,False
布尔类型看起来非常简单?但是我想问下大家有哪值 可转换为False?
因为这才是重点?市面上的文章缺少的就是这种归纳对比的文章,大家都知道的内容你再复述一遍?
能提高?死读书而已。。
print(bool(0)) # False
print(bool(0.0)) # False
print(bool(0j)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(())) # False
print(bool({})) # False
print(bool(set())) # False
print(bool(None)) # False
print(bool(False)) # False
4.None
这个类型最简单?但是大家有没有思考过为啥各种编程语言都有None?
print(a == b) #False
print(a == c) #False
print(a == d) #False
print(bool(a) == d) #True
还有很多,一篇文章是说不清楚了 我会做一个系列来出 并且添加上我的个人理解!
喜欢的话 请多多关注 和支持!再次,感谢!