发送`char`作为函数的输入参数

时间:2019-05-10 09:46:52

标签: python function class parameters

我的问题很简单:是否可以在python程序的开头发送给定类功能的char

 class barberShop(object):

     def __init__(self):
         self.nBlock = 0
         self.nClients = 0
         self.nChairsOccupied = 0
         #self.event = e

     def throwEvent(self, e):
         if e is 'A':
             t = int(random.expovariate(1 / 20))


 if __name__ == '__main__':
     e = 'A'
     barberShop.throwEvent(e)

就我所知,我做不到。我有错正确的方法是什么?

4 个答案:

答案 0 :(得分:0)

您必须首先创建barberShop类的实例:

barberShop_= barberShop()
  上面代码段中的

throwEvent是一个实例方法。你不及格   “自我”直接来了。相反,您需要在中创建一个实例   为了使用它。该函数的“自我”自变量实际上是   实例被调用。

示例:

a = A()
a.functionA(3)

在您的情况下:

    barberShop_= barberShop()
    barberShop_.throwEvent(e)

解决方案:

if __name__ == '__main__':
    e = 'A'
    barberShop_= barberShop()
    barberShop_.throwEvent(e)

if __name__ == '__main__':
    e = 'A'
    barberShop().throwEvent(e)

答案 1 :(得分:0)

import random 
class barberShop(object):

     def __init__(self):
         self.nBlock = 0
         self.nClients = 0
         self.nChairsOccupied = 0
         #self.event = e
     @staticmethod
     def throwEvent( e):
         if e is 'A':
             return  int(random.expovariate(1 / 20))


if __name__ == '__main__':
     e = 'A'
     print(barberShop.throwEvent(e))

答案 2 :(得分:0)

目前,您有

def throwEvent(self, e):

但是致电barberShop.throwEvent(e),因此会收到类似错误

TypeError: throwEvent() missing 1 required positional argument: 'e'

self意味着您在这样的实例上调用它:

if __name__ == '__main__':
    e = 'A'
    shop = barberShop()
    shop.throwEvent(e)

按现状,throwEvent不会执行任何操作,因此您看不到什么,但错误会停止。


您可以使用一些黑客手段,例如:

barberShop.throwEvent(None, e)

如果您在实例上调用该函数,该函数将向其发送实例,因此您可以想到

shop.throwEvent(e)

相同
barberShop.throwEvent(shop, e)

如果没有实例,请改用None

当然,如果您永远不想在实例上调用此方法,请不要使其成为实例方法。从函数中删除self

def throwEvent(e):
     if e is 'A':
         t = int(random.expovariate(1 / 20))

在这种情况下,我想知道为什么它在您的课程中。

答案 3 :(得分:0)

您在这里混合了两件事,您已经将throwEvent定义为类方法,但是您像静态方法一样调用它,您需要确定一种方法

因此,如果您决定将其作为类方法,则需要使用类对象来调用它

import random

class barberShop(object):

    def __init__(self):
        self.nBlock = 0
        self.nClients = 0
        self.nChairsOccupied = 0
        # self.event = e

    #It is a class method
    def throwEvent(self, e):
        if e is 'A':
            t = int(random.expovariate(1 / 20))

#Using class instance object to call throwEvent
e = 'A'
bs = barberShop()
bs.throwEvent(e)

如果您确定它是静态方法,则需要使用@staticmethod装饰器将其定义为静态方法,并摆脱self

import random

class barberShop(object):

    def __init__(self):
        self.nBlock = 0
        self.nClients = 0
        self.nChairsOccupied = 0
        # self.event = e

    #It is a static method
    @staticmethod
    def throwEvent(e):
        if e is 'A':
            t = int(random.expovariate(1 / 20))

#Using class name to call throwEvent
e = 'A'
barberShop.throwEvent(e)