将变量传递到另一个Python类中

2024-09-30 18:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生,目前正在我的大学学习python。我被教授要我们写的一个程序困住了。我认为我有他想要的大部分工作,除了在类通信中正确地将变量传递给方法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非常陌生。如果有人能让我走上正轨那就太好了。我运行它时不断出错。你知道吗


Tags: andtheselfifevalwillclassprint
1条回答
网友
1楼 · 发布于 2024-09-30 18:28:38

问题是,当您尝试从Traffic类调用方法时,尚未实际实例化该类的实例:

Traffic.getClass(self, throughput, delay)

我认为您可能应该阅读pythonclass documentation,以便更好地了解类的工作方式,但解决方案的快速修复方法是将该行替换为以下内容:

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

另外,您使用的是Python2.7还是Python3?不管怎样,在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代码,然后执行,这是非常非常糟糕的事情。你知道吗

相关问题 更多 >