def __init__(self,a,b,n): self.__a=a self.__b=b self.__n=n
时间: 2023-05-22 12:04:09 浏览: 53
这是一个Python类的构造函数,用于初始化类的实例化对象的属性值。其中a、b、n是输入参数,表示某些属性的初始值。构造函数通常被称为__init__,而且在Python中通常应该使用双下划线(_)表示该方法只能在类内部使用。
相关问题
class Point: def __init__(self, x, y): self.__x = x self.__y = y def __add__(self, other): x = self.__x + other.__x y = self.__y + other.__y return Point(x, y) def __sub__(self, other): x = self.__x - other.__x y = self.__y - other.__y return Point(x, y) def __mul__(self, a): x = self.__x * a y = self.__y * a return Point(x, y) def __truediv__(self, a): x = self.__x / a y = self.__y / a return Point(x, y) r1 = Point(10, 20) r2 = Point(5, 5) print(r1+r2) print(r1-r2) print(r1*2) print(r1/2)代码改进,输出向量坐标
为了输出向量坐标,我们可以在 Point 类中添加一个方法来返回坐标的元组,如下所示:
```python
class Point:
def __init__(self, x, y):
self.__x = x
self.__y = y
def __add__(self, other):
x = self.__x + other.__x
y = self.__y + other.__y
return Point(x, y)
def __sub__(self, other):
x = self.__x - other.__x
y = self.__y - other.__y
return Point(x, y)
def __mul__(self, a):
x = self.__x * a
y = self.__y * a
return Point(x, y)
def __truediv__(self, a):
x = self.__x / a
y = self.__y / a
return Point(x, y)
def get_coordinates(self):
return (self.__x, self.__y)
```
然后我们就可以使用这个方法来输出向量坐标了,示例如下:
```python
r1 = Point(10, 20)
r2 = Point(5, 5)
print(r1+r2.get_coordinates()) # 输出 (15, 25)
print(r1-r2.get_coordinates()) # 输出 (5, 15)
print(r1*2).get_coordinates()) # 输出 (20, 40)
print(r1/2).get_coordinates()) # 输出 (5.0, 10.0)
```
完善代码:import math class Triangle: def __init__(self, a, b, c): self.__a = a self.__b = b self.__c = c def get_area(self): h = (self.__a+self.__b+self.__c)/2 s = math.sqrt(h*(h-self.__a)*(h-self.__b)*(h-self.__c)) print(f'三角形的面积:{s}') tri = Triangle(3, 4, 5)
代码已经很完整了,只需要添加一行代码来调用 `get_area()` 方法即可计算三角形的面积,如下所示:
```
tri.get_area()
```
完整代码如下:
```python
import math
class Triangle:
def __init__(self, a, b, c):
self.__a = a
self.__b = b
self.__c = c
def get_area(self):
h = (self.__a+self.__b+self.__c)/2
s = math.sqrt(h*(h-self.__a)*(h-self.__b)*(h-self.__c))
print(f'三角形的面积:{s}')
tri = Triangle(3, 4, 5)
tri.get_area()
```
输出结果为:
```
三角形的面积:6.0
```