https://github.com/Visualize-ML
2. 定义类和对象
在Python中,可以通过class
关键字来定义一个类,类中可以包含属性和方法,然后通过实例化对象来使用类中的属性和方法。
示例代码:定义一个矩形类
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def circumference(self):
return 2 * (self.width + self.height)
def area(self):
return self.width * self.height
rect = Rectangle(5, 10)
print('矩形周长:', rect.circumference())
print('矩形面积:', rect.area())
3. 定义属性
类中的属性可以通过__init__
方法初始化。下面是定义一个名为Chicken
的类的示例。
示例代码:定义一个鸡类
class Chicken:
def __init__(self, name, age, color, weight):
self.name = name
self.age = age
self.color = color
self.weight = weight
chicken_01 = Chicken("小红", 1, "黄色", 1.5)
print('小鸡的名字:', chicken_01.name)
print('小鸡的年龄:', chicken_01.age)
print('小鸡的颜色:', chicken_01.color)
print('小鸡的体重:', chicken_01.weight)
4. 定义方法
类中的方法可以定义在类内部,用来操作类的属性。
示例代码:定义一个列表统计类
class ListStatistics:
def __init__(self, data):
self.data = data
def list_length(self):
return len(self.data)
def list_sum(self):
return sum(self.data)
def list_mean(self):
return sum(self.data) / self.list_length()
def list_variance(self, ddof=1):
mean = self.list_mean()
sum_squares = sum((x - mean) ** 2 for x in self.data)
return sum_squares / (self.list_length() - ddof)
data = [8.8, 1.8, 7.8, 3.8, 2.8, 5.6, 3.9, 6.9]
float_list = ListStatistics(data)
print("列表长度:", float_list.list_length())
print("列表和:", float_list.list_sum())
print("列表平均值:", float_list.list_mean())
print("列表方差:", float_list.list_variance())
5. 使用装饰器
装饰器用于在不修改函数代码的情况下,为函数添加额外的功能或修改函数的行为。
示例代码:使用装饰器定义列表统计类
class ListStatistics:
def __init__(self):
self._data = []
@property
def data(self):
return self._data
@data.setter
def data(self, new_list):
if all(isinstance(x, (int, float)) for x in new_list):
self._data = new_list
else:
print("错误:列表中元素必须全部是数值")
@classmethod
def _are_all_numeric(cls, input_list):
return all(isinstance(x, (int, float)) for x in input_list)
data = [8.8, 1.8, 7.8, 3.8, 2.8, 5.6, '3.9', 6.9]
float_list_obj = ListStatistics()
float_list_obj.data = data # 会输出错误消息
6. 父类和子类
在OOP中,父类和子类之间是一种继承关系。子类可以继承父类的属性和方法,并且可以定义自己的属性和方法。
示例代码:定义动物类及其子类
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(f"{self.name} is eating.")
def sleep(self):
print(f"{self.name} is sleeping.")
class Chicken(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def lay_egg(self):
print(f"{self.name} is laying an egg.")
chicken1 = Chicken("chicken1", 1, "white")
chicken1.eat()
chicken1.lay_egg()