twoSum理解python中的类、方法、对象(类的实例)
1 #self实际是类的实例 2 3 class A: 4 def func(self): 5 print(self) #指向的是类的实例 6 print(self.__class__) #指向的是类 7 8 a = A() 9 a.func() 10 #<__main__.A object at 0x02C40F10> ,显然是A() 11 #<class '__main__.A'> 12 13 #a=A() a.func()过程等价于 14 A.func(a) 15 16 17 #类属性 18 19 class Footballer: 20 21 # 构造函数,创建对象时自动执行的方法,运行student = Footballer("马冬梅",18) 即会执行__init__ 22 23 def __init__(self,name,age): #self==类的实例,即self==student 24 self.age=age #定义实例变量self.r 25 print("我叫:",name,"今年",age,"岁") 26 27 # 定义类变量(在类中但是不在方法中的变量) 28 name = 'test' #此时self对象才有了name属性(self.name) 29 30 # 定义类方法必须要加上self形参 31 def speak(self): 32 print('name:'+self.name) 33 print('age:'+str(self.age)) 34 35 36 student = Footballer("马冬梅",18) 37 student.speak() 38 39 Output: 40 我叫: 马冬梅 今年 18 岁 41 name:test 42 age:18 43 44 45 #twoSum两数之和 46 #solution 1 47 48 class Solution: 49 def __init__(self, nums, target): #构造函数,创建对象即运行 50 self.n=nums 51 self.t=target 52 53 def twoSum(self): 54 num_dict = dict() 55 for index, value in enumerate(self.n): 56 sub = self.t - value 57 if sub in num_dict.keys(): 58 return [num_dict[sub], index] 59 else: 60 num_dict[value] = index 61 62 return [] 63 a=Solution([1,2,7,11],9) #要在创建对象时传参,那需要构造函数。这一步运行了实际sef.n,self.t已经执行了。 64 a.twoSum() 65 66 67 #solution 2 68 class Solution: 69 def twoSum(self, nums, target): 70 num_dict = dict() 71 for index, value in enumerate(nums): 72 sub = target - value 73 if sub in num_dict.keys(): 74 return [num_dict[sub], index] 75 else: 76 num_dict[value] = index 77 78 return [] 79 a=Solution() #创建对象不传参 80 a.twoSum([1,2,7,11],9) #对象调用方法再传参 81 82 #以上两行调用相当于: 83 Solution().twoSum([2,7,11,15],9) 84 85 86 87 #Solution 3 #python切片 88 class Solution: 89 def twoSum(self, nums, target): 90 for i in range(len(nums)): 91 if target-nums[i] in nums[i+1:]: 92 return[i,nums.index(target-nums[i])] 93 94 95 #solution 4 #通过列表值,去索引列表index 96 class Solution: 97 def twoSum(self, nums, target): 98 for index, value in enumerate(nums): 99 sub = target - value 100 if sub in nums: 101 return [index,nums.index(sub)]