如何检查函数是否已定义?Python角

2024-10-01 15:42:27 发布

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

我对编程还很陌生,花了3个小时试图弄明白为什么这不管用,我就做不到

import wget

print("Serverstall By Logix1") #Prints Info At start

print("Here comes the real code!")

class ServerSelector:
    def _init__(self, ServerType, PowerRequired):
        self.ServerType = USRchoice1
        self.PowerRequired = USRchoice2
    USRchoice1 = input("What server type to do want to create?")
    USRchoice2 = input("Please choose the amount of ram required?")
    def GarrysMod(self):
        if USRchoice1 is ("GarrysMod"):
            print("Nice! Great Choice!")

它在输入GarrysMod后不打印Nice Great Choice?有人知道怎么了吗?你知道吗


Tags: thetoselfinputdef编程niceprint
2条回答

Python提供了各种方法来检查是否定义了变量/方法。你知道吗

对于全局变量/函数

def C():
   pass

MY_FUNC_NAME = "C"
NOT_MY_FUNC_NAME = "c"

print(MY_FUNC_NAME in locals()) # True
print(NOT_MY_FUNC_NAME in locals()) # False

对于类方法/变量

class MyClass:
   def C():
      pass


MY_METH_NAME = "C"
NOT_MY_METH_NAME = "c"

print(MY_METH_NAME in dir(MyClass)) # True
print(NOT_MY_METH_NAME in dir(MyClass)) # False

事物USRchoice1和2不是self的一部分,您不调用函数。你没有实例化一个对象。所以什么都没发生。你知道吗

import wget

print("Serverstall By Logix1") #Prints Info At start

print("Here comes the real code!")

class ServerSelector:
    def __init__(self, ServerType, PowerRequired):
        self.ServerType = ServerType
        self.PowerRequired = PowerRequired
        if self.ServerType is ("GarrysMod"):
            print("Nice! Great Choice!")

USRchoice1_tmp = input("What server type to do want to create?")
USRchoice2_tmp = input("Please choose the amount of ram required?")
My_selector = ServerSelector(USRchoice1_tmp, USRchoice2_tmp )

因此,似乎不是你的函数存在的问题,而是你的代码的一般结构。 编辑/添加:init的拼写必须是__init__,两边都有两个。请注意,上面的代码开头只有一个。你知道吗

相关问题 更多 >

    热门问题