import math
"""2
实例(Instance):把类通过赋值符(=)赋值给一个变量,这个过程称为实例化过程,这个变量就是实例。
实例化过程实质是在内存中建立一个独立的实例对象。
在类里面定义的函数,也可以叫方法。
但在实例里调用时,一律叫方法。
如:c1.circle_girth(),在这里 circle_girth() 称为方法。
实例通过点号(.)可调用属性、方法两个对象。
如:
c1.radius
c1.circle_area()
##################################
属性(Property)是通过 __init__ 函数定义,并通过 self 传递给实例的一种数据类型。
1、属性初始化
1.1 在 __init__ 里直接初始化值
1.2 传递参数初始化
2、属性值修改
2.1 直接对属性值进行修改 c = Circle() c.radius = 15
2.2 通过方法对属性值进行修改
3、把类赋给属性
"""
r = int(input('请输入圆的半径:'))
class Circle0: # 1.1 在 __init__ 里直接初始化值
"""求圆的面积"""
def __init__(self):
self.radius = 0
def set_new_radius(self, radius): # 通过方法对属性值进行修改 定义了修改半径 radius 的函数
self.radius = radius
c0 = Circle0()
c0.radius = 12 # 2.1 直接对属性值修改 c = Circle() c.radius = 15
print(c0.radius) # 12
c0.set_new_radius(r) # 输入的值
print(c0.radius)
class Circle1: # 1.2 传递参数初始化
"""求圆的面积"""
def __init__(self, radius):
self.radius = radius
c1 = Circle1(r)
print(c1.radius)
#######################################
# 3、把类赋给属性
class Color:
"""颜色类,可根据给定索引设定颜色列表里的一种颜色"""
def __init__(self, index=0):
self.the_color = ['white', 'red', 'black', 'yellow', 'green', 'grey']
self.index = index
def set_color(self): # 设定颜色的函数
return self.the_color[self.index]
class Circle:
"""展示圆的面积、颜色的类"""
def __init__(self, radius, color=0):
self.radius = radius
self.color = Color(color).set_color()
def show_detail(self): # 展示圆的面积、颜色的函数
c_color = self.color
c_area = self.radius * self.radius * math.pi
return c_color, c_area
idx = int(input('请输入颜色索引(0-5):'))
c = Circle(r, idx) # 实例化圆 c
tup = c.show_detail() # 调用圆 c 的 show_detail() 方法
print('圆 c 的颜色:', tup[0])
print('圆 c 的面积:', tup[1])