模块与pygam一起工作不正常

2024-09-25 16:22:57 发布

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

我不能使用主模块中其他模块中的函数

#MAIN FILE - mainfile.py

#Imports / display / pygame.init

from file2 import *

font=pygame.font.SysFont("Arial",35)

example(1) #THERE I DEFINE DE CLASS

Text=font.render(list1[0],0,(255,255,255))
win.blit(Text,(5,5))


#while loop

#file 2 - file2.py


class example:
    def __init__(self, whichlist):
        global list1
        if whichlist==1:
            list1=["bird", "bird2", "bird3"]
        elif whichlist==2:
            list1=["bird", "bird2", "bird3"]

        #more code


我知道我可以在file2中定义示例类,但是我想在主文件中定义它


Tags: 模块函数textpy定义initexamplepygame
1条回答
网友
1楼 · 发布于 2024-09-25 16:22:57

在您的示例中,function可能比class更好。与其使用global,不如使用return

file2.py

def get_list(whichlist)
    if whichlist == 1:
       return ["bird", "bird2", "bird3"]
    elif whichlist == 2:
       return ["bird", "bird2", "bird3"]
    #else:
    #   return []

file1.py

from file2 import get_list

list1 = get_list(1)

如果您真的需要使用类,那么您应该在类中创建使用return的方法

对类使用CamelCaseNames也有一个很好的规则——它意味着Example而不是“example”

file2.py

class Example:

    def get_list(self, whichlist):
        if whichlist == 1:
            return ["bird", "bird2", "bird3"]
        elif whichlist == 2:
            return ["bird", "bird2", "bird3"]
        #else:
        #    return []

file1.py

from file2 import Example

ex = Example()
list1 = ex.get_list(1)

最终

list1 = Example().get_list(1)

相关问题 更多 >