gpt4 book ai didi

python - 如何对类中的多个方法设置偏差?

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:04 25 4
gpt4 key购买 nike

免责声明:Python 新手

我的代码

class summation():

def __init__(self, num_1, num_2):

self.add_1 = num_1 + num_2
self.multiply = num_1 * num_2
self.divide = num_1 / num_2
self.difference = num_1 - num_2

def summate(self):
return '{}'.format(self.add_1)

def mult(self):
return '{}'.format(self.multiply)

def divis(self):
return '{}'.format(self.divide)

def diff(self):
return '{}'.format(self.difference)

input_values = summation(int(input()), int(input()))

print('Sum =', input_values.add_1)
print('Multiplied =', input_values.multiply)
print('Divided =', input_values.divide)
print('The difference between the two values is ',input_values.difference)```

我想包含一个偏差方法,它将获取用户输入的值并对它们应用可以轻松更改的偏差

即用户输入 (2) 和 (3),偏差对它们应用 1.02 乘数

所以事情是这样开始的

bias = 1.04

def apply_bias(self):
return input_values * bias

显然这不起作用,但它给了你一个想法

大家有什么想法吗?干杯

最佳答案

不确定您打算做什么,但我认为其中之一应该适合您。

bias = 1.04

# Accept two values multiply them and the bias and return one result
def apply_bias(self, first, second):
return (first * second) * bias

# or if you want to accept two values and return a tuple of two results
def apply_bias(self, first, second):
return first * bias, second * bias

阅读您的评论后编辑我想我理解得更好了。试试这个:

class Summation:
def __init__(self, first, second, bias=1.04):
self.first = first
self.second = second
self.bias = bias

def summate(self, include_bias=False):
result = self.first + self.second
if not include_bias:
return result
return result * self.bias

def mult(self, include_bias=False):
result = self.first * self.second
if not include_bias:
return result
return result * self.bias

def divis(self, include_bias=False):
result = self.first / self.second
if not include_bias:
return result
return result * self.bias

def diff(self, include_bias=False):
result = self.first - self.second
if not include_bias:
return result
return result * self.bias

def apply_bias(self, bias):
self.bias = bias

def summary(self, include_bias=False):
print(f'Sum = {input_values.summate(include_bias)}')
print(f'Multiplied = {input_values.mult(include_bias)}')
print(f'Divided = {input_values.divis(include_bias)}')
print(f'The difference between the two values is {input_values.diff(include_bias)}')


input_values = Summation(int(input("first:")), int(input("second:")))
input_values.summary()
str_bias = input("bias:")
if str_bias:
input_values.apply_bias(float(str_bias))
input_values.summary(True)

这将打印您的描述内容

first:2
second:2
Sum = 4
Multiplied = 4
Divided = 1.0
The difference between the two values is 0
bias:1.04
Sum = 4.16
Multiplied = 4.16
Divided = 1.04
The difference between the two values is 0.0

关于python - 如何对类中的多个方法设置偏差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59900209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com