python常用的数据类型有:整型,浮点型,字符串,列表,字典,集合,元组。
虽然python是弱类型语言,声明变量时不需要像java那样显示声明数据的类型。
其中不可变类型有,整型,浮点型,字符串String,元组tuple。
可变类型有,列表list,字典dictionary,集合set。
数字Number类型有int, float, bool, complex复数。
这里指的是python3, int作为唯一一种整数类型,表示长整型,没有python2的Long.
分享一个小方法,判断变量的数据类型可用内置的type()函数或isinstance(var, data_type)来判断。
例子:
1. int
def data_type():
# 1. int
a = 1111
print(a)
print("type of a", type(a))
print("a's type", isinstance(a, int))
输出:1111
type of a <class 'int'>
a's type True
2. class
先定义2个类,父类为dish, 子类为cold_dish
class dish:
def __init__(self, value):
self.value = value
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
子类cold_dish在父类的基础上增加了2个属性,dish_name, dish_price
class cold_dish(dish):
def __init__(self, dish_name, dish_price):
super()
self.dish_name = dish_name
self.dish_price = dish_price
def set_value(self, value):
super().set_value(value)
def get_value(self):
return super().get_value()
def set_dish_name(self, dish_name):
self.dish_name = dish_name
def get_dish_name(self):
return self.dish_name
def set_dish_price(self, dish_price):
self.dish_price = dish_price
def get_dish_price(self):
return self.dish_price
接下来使用type(),isinstance()函数来判断
# 2. class
dishA = dish("shaoe")
dishCd = cold_dish("shaoya", 25)
print(type(dishA))
print("dishA's type", isinstance(dishA, dish))
print("dishCd's type", isinstance(dishCd, cold_dish))
print("dishCd's type", isinstance(dishCd, dish))
print("dishCd's type", type(dishCd))
print("dishA.get_value=", dishA.get_value())
print("dishCd.get_dish_name=", dishCd.get_dish_name())
输出:<class '__main__.dish'>
dishA's type True
dishCd's type True
dishCd's type True
dishCd's type <class '__main__.cold_dish'>
dishA.get_value= shaoe
dishCd.get_dish_name= shaoya
type()返回的是类的类型,当使用type(dishCd)时,返回的cold_fish类型,而不是父类dish
当使用isinstance(dishCd, dish)时,返回的是True, 代表dishCd是父类dish的类型
当使用isinstance(dishCd, cold_dish)时,返回的是True, 代表dishCd是cold_dish类型
3. str: 字符串String大类的表示
# 3. str是String大类的 表示
str1 = "love me, love my dog! "
print("str1 double", str1 * 2)
print("type of str1=", type(str1)) # type of str1= <class 'str'>
print("type of str1 = str?", isinstance(str1, str)) # True
输出:
str1 double love me, love my dog! love me, love my dog!
type of str1= <class 'str'>
type of str1 = str? True
4. bool:
# 4. bool类型
bl = False
print("type of bl=", type(bl)) # type of bl= <class 'bool'>
print("type of bl=bool?", isinstance(bl, bool))
输出:
type of bl= <class 'bool'>
type of bl=bool? True
5. float:
# 5. float
fl = 2.1
print("type of fl=", type(fl)) # type of fl= <class 'float'>
print("type of fl= float?", isinstance(fl, float))
输出:
type of fl= <class 'float'>
type of fl= float? True
6. complex复数
# 6. complex 复数
comp = 3 - 4j
compl = 3 + 4j
print("type of comp=", type(comp)) # type of comp= <class 'complex'>
print("type of comp=complex?", isinstance(compl, complex))
输出:
type of comp= <class 'complex'>
type of comp=complex? True
以上为python的6种基本数据类型。基础夯实,得多多练习。