# __class__表示当前操作的对象是什么 # 1、如何让b的对象实现a的shou方法 # class A: # def show(self): # print("A-show") # # class B(A): # def show(self): # print("B-show") # # # obj = B() # # # print(obj.__class__) # # obj.__class__=A # # obj.show() # 2、这段代码怎么才能运行,(为了让对象的实例可以被直接调用,实现call方法) # class A(object): # def __init__(self,a,b): # self.__a = a # self.__b = b # def myprint(self): # print("a=",self.__a,"b=",self.__b) # # def __call__(self, num): # # print("call:",num + self.__a) # # # a = A(10,20) # # a.myprint() # # # # a(100) # 3、# __new__,和 __init__ # class B: # def fn(self): # print("B-fn") # def __init__(self): # print("B-init") # # class A: # def fn(self): # print("A-fn") # def __new__(cls, a): # print("new",a) # if a > 10: # return super(A,cls).__new__(cls) # return B # def __init__(self,a): # print("init",a) # # # a1 = A(5) # # a1.fn(1) # # a2 = A(20) # # a2.fn() # 4、list or dict # ls = [1,2,3,4] # list1 = [i for i in ls if i>2] # print(list1) #[3, 4] # # list2 = [i*2 for i in ls if i>2] # print(list2) #[6, 8] # # dic1 = {x:x**2 for x in (2,4,6)} # print(dic1) #{2: 4, 4: 16, 6: 36} # # dic2 = {x:‘item‘+str(x**2) for x in (2,4,6)} # print(dic2) #{2: ‘item4‘, 4: ‘item16‘, 6: ‘item36‘} # # set1 = {x for x in ‘hello world‘ if x not in ‘low level‘} # print(set1) #{‘d‘, ‘h‘, ‘r‘} # 6、全局or局部 # num = 9 # def f1(): # global num # num = 20 # # print(num) # def f2(): # print(num) # f2() # f1() # f2() # class A: # def __init__(self,a,b): # self.a1 = a # self.b1 = b # print("init") # def mydefault(self): # print("default") # def __getattr__(self, item): # print("getattr") # return self.mydefault() # # a1 = A(10,20) # a1.fn1() # __all__ = ["mod2","mod1"] # 卸载iniit里,只导入这两个模块 # # def mulby(num): # def gn(val): # return num * val # return gn # # zw = mulby(7) # print(zw(6)) def strtest(num): str1 = "first" for i in range(num): str1 +="x" return str1 # python的str是个不可变对象,每次迭代,都会生成新的str对象来存储新的字符串,num越大,创建的str对象越多,内存消耗越大。 # numbers = [x*x for x in range(20) if x % 3 == 0] # numbers = {x * x for x in range(0, 20) if x % 3 == 0} # numbers = {x: x * x for x in range(0, 20) if x % 3 == 0} a = "I love python" reverse_a = a[::-1] print(reverse_a) cities = ["beijin","tianjin","shenzhegn"] for index,city in enumerate(cities,1): print(index,":",city)