print(type(1))
print(id(1))
print(dir(1)) # 查看属性和方法
<class 'int'> 4338286832 ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
print(type("a"))
print(id("a"))
print(dir("a"))
<class 'str'> 4339687920 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(abs(-1))
print(id(abs))
print(type(abs))
print(dir(abs))
1 4338894384 <class 'builtin_function_or_method'> ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
a = complex(2,5)
b = a
print(id(a))
print(id(b))
4709526608 4709526608
print("abc".upper())
print((1+2j).real)
print((1+2j).imag)
ABC 1.0 2.0
直接赋值就能增加对应的属性
OOP:面向对象编程
类名使用驼峰命名法,CamelCase
自定义类:class语句
class ClassName:
def __init__(self,*param): # 构造函数
print("哈喽啊")
def another_method(self,*param):
print("你好呀")
例:创建一个力对象
class Force:
def __init__(self,x,y):
self.fx , self.fy = x,y
def show(self):
print("fx = {} , fy = {}".format(self.fx,self.fy))
def add(self,force2):
# 不改自己,生成一个新的对象
x = self.fx+force2.fx
y = self.fy+force2.fy
return Force(x,y)
# 生成两个力对象
f1 = Force(0,1)
f1.show()
f2 = Force(3,4)
f2.show()
f_new = f1.add(f2)
f_new.show()
fx = 0 , fy = 1 fx = 3 , fy = 4 fx = 3 , fy = 5
由上面,发现,不用全列出来,随时出现变量名,随时用。
这就是动态特性。
import os.path
class FileManager:
def __init__(self,filepath,filename):
self.file = open(os.path.join(filepath,filename))
print("文件打开成功")
def __del__(self):
self.file.close()
del self.file
print("文件已关闭")
f = FileManager("/Users/caiguu/PycharmProjects/pythonLearn","新时代.txt")
del f
文件打开成功 文件已关闭
class Force:
def __init__(self,x,y):
self.fx , self.fy = x,y
def show(self):
return "fx = {} , fy = {}".format(self.fx,self.fy)
def add(self,force2):
# 不改自己,生成一个新的对象
x = self.fx+force2.fx
y = self.fy+force2.fy
return Force(x,y)
__add__ = add
__str__ = show
def __mul__(self, n): # f*3.5这种形式
x,y = self.fx*n,self.fy*n
return Force(x,y)
def __eq__(self, other):
return self.fx==other.fx and \
self.fy == other.fy
def __rmul__(self, n): # 3.5*f这种形式
x,y = self.fx*n,self.fy*n
return Force(x,y)
# 也可以直接__rmul__ = __mul__
f1 = Force(1,4)
f2 = Force(5,1)
print(f1+f2)
print(f1==f2)
print(3.5*f1)
print(f2*1.14)
f3 = f1 + f2
print(f3)
fx = 6 , fy = 5 False fx = 3.5 , fy = 14.0 fx = 5.699999999999999 , fy = 1.14 fx = 6 , fy = 5
name = ["John","Bob","Alice","olg","肖+号"]
name.sort()
print(name)
name = ["John","Bob","Alice","olg","肖+号"]
name.sort(reverse=True)
print(name)
name = ["John","Bob","Alice","olg","肖+号"]
name_new = sorted(name)
print(name)
print(name_new)
['Alice', 'Bob', 'John', 'olg', '肖+号'] ['肖+号', 'olg', 'John', 'Bob', 'Alice'] ['John', 'Bob', 'Alice', 'olg', '肖+号'] ['Alice', 'Bob', 'John', 'olg', '肖+号']
def __lt__(self,y)
class Force:
def __init__(self,x,y):
self.fx , self.fy = x,y
def show(self):
return "fx = {} , fy = {}".format(self.fx,self.fy)
def add(self,force2):
# 不改自己,生成一个新的对象
x = self.fx+force2.fx
y = self.fy+force2.fy
return Force(x,y)
__add__ = add
__str__ = show
__repr__= show
def __mul__(self, n): # f*3.5这种形式
x,y = self.fx*n,self.fy*n
return Force(x,y)
def __eq__(self, other):
return self.fx==other.fx and \
self.fy == other.fy
def __rmul__(self, n): # 3.5*f这种形式
x,y = self.fx*n,self.fy*n
return Force(x,y)
# 也可以直接__rmul__ = __mul__
def __lt__(self, y):
value1 = self.fx**2+self.fy**2
value2 = y.fx**2+y.fy**2
return value1<value2
f1 = Force(1,4)
f2 = Force(5,5)
print(f1<f2)
forces = [Force(1,4),Force(2,3),Force(6,6),Force(1,1)]
forces.sort()
print(forces)
for f in forces:
print(f)
True [fx = 1 , fy = 1, fx = 2 , fy = 3, fx = 1 , fy = 4, fx = 6 , fy = 6] fx = 1 , fy = 1 fx = 2 , fy = 3 fx = 1 , fy = 4 fx = 6 , fy = 6
学生类,成绩由高到低排序:
class Student:
def __init__(self,name,grade):
self.name = name
self.grade = grade
def __lt__(self, other):
return self.grade>other.grade
def __str__(self):
return "学生%s,成绩%d" % (self.name,self.grade)
__repr__=__str__
s = list()
s.append(Student("Jack",100))
s.append(Student("Alice",99))
s.append(Student("Bob",59))
s.append(Student("olg",63))
s.append(Student("x+h",95))
s.append(Student("Niconiconi",93))
print(s)
s.sort()
print(s)
[学生Jack,成绩100, 学生Alice,成绩99, 学生Bob,成绩59, 学生olg,成绩63, 学生x+h,成绩95, 学生Niconiconi,成绩93] [学生Jack,成绩100, 学生Alice,成绩99, 学生x+h,成绩95, 学生Niconiconi,成绩93, 学生olg,成绩63, 学生Bob,成绩59]
根据调试得出结论,无论是否reverse,只调用了lt方法。
当然还可以定义其他的比较符,重载相关的符号运算。
例:车辆续航里程
class Car:
def __init__(self,name):
self.name = name
self.remain_mile = 0
def fill_fuel(self,miles):
self.remain_mile += miles
def run(self,miles):
if self.remain_mile >= miles:
self.remain_mile -= miles
print("%s: 车辆跑了 %d 公里!" % (self.name,miles))
else:
print("%s: 燃料耗尽!" % self.name)
class GasCar(Car):
def fill_fuel(self,gas):
self.remain_mile += gas * 6
class ElecCar(Car):
def fill_fuel(self,power):
self.remain_mile += power * 3
gcar = GasCar("BMW")
gcar.fill_fuel(50)
gcar.run(200)
ecar = ElecCar("Tesla")
ecar.fill_fuel(60)
ecar.run(200)
BMW: 车辆跑了 200 公里! Tesla: 燃料耗尽!
class GasCarNew(Car):
def __init__(self,name,capacity):
super().__init__(name)
self.capacity = capacity
gcar_new = GasCarNew("BMW",114514)
gcar_new.fill_fuel(20)
GasCar.fill_fuel(gcar_new,50)
gcar_new.run(30)
GasCar.run(gcar_new,50)
BMW: 车辆跑了 30 公里! BMW: 车辆跑了 50 公里!
class People:
def __init__(self,name,city):
self.name = name
self.city = city
def moveto(self,newcity):
self.city = newcity
def __str__(self):
return "<name = %s , city = %s>" % (self.name,self.city)
def __lt__(self, other):
return self.name < other.name
__repr__ = __str__
p1 = People("张三","河北承德")
p2 = People("肖加号","福建莆田")
p3 = People("奥利给","上海浦东")
p4 = People("olg","北京海淀")
ls = [p1,p2,p3,p4]
print(ls)
ls.sort()
print(ls)
p3.moveto("北京东城")
print(p3)
[<name = 张三 , city = 河北承德>, <name = 肖加号 , city = 福建莆田>, <name = 奥利给 , city = 上海浦东>, <name = olg , city = 北京海淀>] [<name = olg , city = 北京海淀>, <name = 奥利给 , city = 上海浦东>, <name = 张三 , city = 河北承德>, <name = 肖加号 , city = 福建莆田>] <name = 奥利给 , city = 北京东城>
class Teacher(People):
def __init__(self,name,city,school):
self.name = name
self.city = city
self.school = school
def moveto(self,newschool):
self.school = newschool
def __lt__(self, other):
return self.school < other.school
def __str__(self):
return "<name = %s , city = %s , school = %s>" % (self.name,self.city,self.school)
__repr__ = __str__
t1 = Teacher("zzz","河北承德","BJFU")
t2 = Teacher("xjh","福建莆田","BUPT")
t3 = Teacher("jxh","福建莆田","THU")
t4 = Teacher("hjx","福建莆田","PKU")
ls = [t1,t2,t3,t4]
print(ls)
ls.sort()
print(ls)
t2.moveto("加里敦大学")
print(ls)
[<name = zzz , city = 河北承德 , school = BJFU>, <name = xjh , city = 福建莆田 , school = BUPT>, <name = jxh , city = 福建莆田 , school = THU>, <name = hjx , city = 福建莆田 , school = PKU>] [<name = zzz , city = 河北承德 , school = BJFU>, <name = xjh , city = 福建莆田 , school = BUPT>, <name = hjx , city = 福建莆田 , school = PKU>, <name = jxh , city = 福建莆田 , school = THU>] [<name = zzz , city = 河北承德 , school = BJFU>, <name = xjh , city = 福建莆田 , school = 加里敦大学>, <name = hjx , city = 福建莆田 , school = PKU>, <name = jxh , city = 福建莆田 , school = THU>]
这是对内置类型的继承!
class MyList(list):
def product(self):
p = 1
for i in range(len(self)):
p *= self[i]
return p
# 也可以 for i in self:; p*=i
ls = MyList([1,1,4,5,1,4,1,9,1,9,8,1])
print(ls)
print(ls.product())
print(MyList.product(ls))
[1, 1, 4, 5, 1, 4, 1, 9, 1, 9, 8, 1] 51840 51840