太久没写python代码了,学机器学习重新拾起python,笔记比较简陋。
目录
一、exception异常
try:
age = int(input("Age: "))
xfactor = 10/age
except ValueError:
print("You didn't enter a valid age.")
#也可以写pass,这部分不能为空。
except ZeroDivisionError:
print("Age cannot be zero.")
else:
print("No exceptions were thrown.")
#还可以这么写:
try:
age = int(input("Age: "))
xfactor = 10/age
except (ValueError, ZeroDivisionError): #!!!
print("You didn't enter a valid age.")
else:
print("No exceptions were thrown.")
finally:
print("HEllo")
#finally中的语句不管前面有无异常都会被执行。
#raise
def calculate_xfactor(age):
if age <= 0:
raise ValueError("Age cannot be 0 or less.")
return 10/age
try:
calculate_xfactor(-1)
except ValueError as error:
print(error)
二、class
object是class的实例。
初始化和类方法
class MyPoint:
default_color = "red" # 可以被实例引用,也可以直接被对象引用。
def __init__(self, x, y): #初始化
self.x = x
self.y = y
@classmethod # 这样的方法可以在不创建类的实例的情况下直接调用。
def zero(cls): # cls是类本身。
return cls(0, 0)
def draw(self):
print(f"Point ({self.x},{self.y})")
#调用类方法
ppoint = MyPoint.zero()
ppoint.draw() #Point (0,0)
point = MyPoint(1, 2)
point.default_color = "yellow" # 实例改,不影响对象。
MyPoint.default_color = "yellow" # 对象修改,影响实例。
print(point.default_color)
print(MyPoint.default_color)
point.draw()
print(point.x)
magic method __str__
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x},{self.y})"
def draw(self):
print(f"Point ({self.x},{self.y})")
point = MyPoint(1, 2)
print(point) # 返回__str__方法
compare object
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
point = MyPoint(1, 2)
other = MyPoint(1, 2)
print(point == other) # False 比较的是两个object在内存中的位置。
__eq__,__gt__改写
注意左右两边是两个下划线,不要打多,也不要打少,否则会报错。
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other): # equal
return self.x == other.x and self.y == other.y
def __gt__(self, other): # greater than
return self.x > other.y and self.y > other.y
point = MyPoint(10, 20)
other = MyPoint(1, 2)
print(point == other) # False, 利用__eq__比较。
print(point > other) # True, 利用__gt__比较。
arithmetic operations
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # equal
return f"({self.x+other.x}, {self.y+other.y})"
point = MyPoint(10, 20)
other = MyPoint(1, 2)
print(point + other) #(11, 22)
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other): # equal
return MyPoint(self.x+other.x, self.y+other.y)
point = MyPoint(10, 20)
other = MyPoint(1, 2)
combined = point+other #新建一个对象存储加法结果。
print(combined.x)
print(combined.y)
字典新增
class TagCloud:
def __init__(self):
self.tags = {}
def add(self, tag): # 给dict新增(key,value)
self.tags[tag] = self.tags.get(tag, 0) + 1
# get是获tag对应的value值。
def __getitem__(self, tag): # 返回key对应的value
return self.tags.get(tag, 0)
def __setitem__(self, tag, count): # 修改key对应value
self.tags[tag] = count
def __len__(self):
return len(self.tags)
cloud = TagCloud()
cloud.add("python")
cloud.add("python")
cloud.add("python")
cloud.add("py")
print(cloud["python"]) # 3
cloud["python"] = 6
print(cloud.tags) # {'python': 6, 'py': 1}
print(len(cloud)) # 2
private members
self.tags = {} 改为 self.__tags = {} 在tags前加__就可以变为private类型
- 修改方式:鼠标悬空在tags单词上,按F2按键,出现一个框,里面有tags,在里面修改成__tags。文件内所有tags都加上了__
- 但即使这样把元素变为私有,外面的函数也可以访问这个私有元素。
- 所以“私有”这个含义,实际上是为我们写程序的一种约定,不要轻易访问私有元素。但实际是可以访问的。
cloud = TagCloud()
print(cloud.__dict__) #输出了 {'_TagCloud__tags': }
#可以利用这个_TagCloud__tags 来访问。
print(cloud._TagCloud__tags)
#即可输出字典中的元素。
属性property
class Product:
def __init__(self, price):
self.__price = price
def get_price(self):
return self.__price
def set_price(self, value):
if value < 0:
raise ValueError("Price cannot be negative.")
self.__price = value
price = property(get_price, set_price)
product = Product(10)
# 价格不能是-50,我们需要加个价格大于0的属性。
print(product.price)
方法二
class Product:
def __init__(self, price):
self.price = price
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative.")
self.__price = value
product = Product(-10)
# 价格不能是-50,我们需要加个价格大于0的属性。
print(product.price)
继承
class Animal:
def eat(self):
print("eat")
class Mammal(Animal): #Mammal继承了Animal
def walk(self):
print("walk")
class Fish(Animal):
def swin(self):
print("swin")
m = Mammal()
m.eat()
覆盖
class Animal:
def __init__(self):
self.age = 1
def eat(self):
print("eat")
class Mammal(Animal):
def __init__(self):
#super().__init__() #加上这句话就不报错了,仍然继承父类中的__init__
self.weight = 2
def walk(self):
print("walk")
m = Mammal()
print(m.weight)
print(m.age) #会报错,因为mammal中的__init__覆盖了父类中的__init__