gpt4 book ai didi

python - 将变量传递给另一个类 python

转载 作者:行者123 更新时间:2023-11-28 22:49:24 26 4
gpt4 key购买 nike

我是 Python 的新手,目前正在我的大学上一门 Python 类(class)。我被困在教授要我们编写的程序上。我认为除了正确地将变量传递给类 Traffic 中的 getClass 方法外,我已经完成了他想要的大部分工作。这是给定的作业:

Step 4:

Steps:

  • Modify the class called Traffic that will have four private attributes: throughput, delay, jitter, loss.
  • Modify the method called getClass within the Traffic class, that will classify traffic as below:
    • Best effort: throughput < 5, delay between 8 and 10
      or
      Throughput between 5 and 10, delay > 8
    • Controlled load: throughput between 5 and 10 , delay <= 8
      or
      Throughput >=10, delay >= 5
    • Guaranteed: throughput >=10, delay < 5

Write a program called testTrafficClass to test the traffic class. The program will have a main() function that will initialize the four attributes of class Traffic, and print the traffic class. It will then prompt the user to change the attributes, and will print traffic class based on the new values.

这是我目前的代码:

def Main():
def __init__(self, throughput = 0, delay = 0, jitter = 0, loss = 0):
self.__throughput = throughput
self.__delay = delay
self.__jitter = jitter
self.__loss = loss

throughput = eval(input("Enter Throughput: "))
delay = eval(input("Enter Delay: "))
jitter = eval(input("Enter Jitter: "))
loss = eval(input("Enter Loss: "))

Traffic.getClass(self, throughput, delay)

class Traffic:
def getClass(self, throughput, delay):
if (throughput<5) and (delay <= 10) and (8<=delay):
print("Best Effort")
if (5<=throughput) and (throughput<=10) and (delay>8):
print ("Best Effort")
if (5<=throughput) and (throughput<=10) and (delay<=8):
print ("Controlled load")
if (throughput >=10) and (delay >=5):
print ("Controlled load")
if (throughput >=10) and (delay <5):
print ("Guaranteed")

Main()

我确信这不是最好或最优雅的代码,因为我是 Python 的新手。如果有人能让我走上正轨,那就太好了。我在运行时不断收到错误消息。

最佳答案

问题是当您尝试从此处调用方法时,您还没有实际实例化 Traffic 类的实例:

Traffic.getClass(self, throughput, delay)

我认为您应该阅读 python class documentation为了更好地了解类是如何工作的,但解决方案的快速解决方案是用以下内容替换该行:

 traffic = Traffic() # Creates an instance of the Traffic class
tclass = traffic.getClass(throughput, delay) # Calls the getClass method on that instance

另外,你是Python 2.7还是Python 3?无论哪种方式,在 input 上调用 eval 都是非常糟糕的做法(在 3 的情况下)或完全不需要(在 2.7 的情况下)。如果预期的输入是 float,您应该改为这样做:

 throughput = float(raw_input("Enter Throughput: ")) # Python 2.7
throughput = float(input("Enter Throughput: ")) # Python 3.X

同样适用于您的其他输入。这确保唯一有效的输入是变成 float 的东西,其他任何东西都会引发异常。按照你现在的方式,用户可以输入任意 python 代码,它就会执行,这是一件非常非常糟糕的事情。

关于python - 将变量传递给另一个类 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23900623/

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