我对 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 theTraffic
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 amain()
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/