如何访问另一个类中的函数

2024-04-26 10:58:58 发布

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

我正在做一个有趣的登录程序,我想知道如何访问另一个class/def中一个class/def中的函数?抱歉,如果我听起来很笨的话,我可是Python里的笨蛋!你知道吗

示例:

class Main()
     def LOL:
        A = 'apples'

我想在这里应用函数A:

def banana:
    B = 'banana'
    print(B + A)

抱歉,如果这是一个相当随机的代码示例,但我真的想不出其他任何东西!你知道吗


Tags: 函数代码程序示例maindefclass笨蛋
1条回答
网友
1楼 · 发布于 2024-04-26 10:58:58
class Main():
   def __init__(self):
      self.A = 'apples' #A is now an instance variable, set to 'apples'

#don't forget parentheses here!
def banana():
   B = 'banana'
   m = Main() #you'll need an instance of main to reference a variable in it...
   print(B + m.A) #m.A gets the variable A from m.

与您的示例更相似,但需要更多代码(使用函数获取变量):

class Main():
   def __init__(self):
      self.A = 'apples' #A is now an instance variable, set to 'apples'
   def LOL(self):
      return self.A
#don't forget parentheses here!
def banana():
   B = 'banana'
   m = Main() #you'll need an instance of main to reference a variable in it...
   print(B + m.LOL()) #m.LOL() will return m.A

相关问题 更多 >