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

时间:2014-07-09 16:47:42

标签: python function class module

我正在制作一个有趣的登录程序,我想知道如何在另一个类/ def中访问一个类/ def中的函数?对不起,如果我听起来很蠢,我就是Python中的菜鸟!

示例:

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

我希望在这里应用函数A:

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

很抱歉,如果它是一个非常随机的代码示例,但我真的想不出别的什么!

1 个答案:

答案 0 :(得分:0)

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