假设我有以下代码
class ter:
def func1()
def func2()
class fg:
def gl1()
def gl2()
ifTrue)
ter.func1() # func1 from class ter
如何从类fg调用类ter的func1? ter.func1()无效。
答案 0 :(得分:3)
由于ter
是该类的名称,ter.func1()
是调用@staticmethod
或(@classmethod
)的语法。通常,您不应该仅仅使用Python中的类来组织函数;相反,你会使用“自由功能”或模块级功能。
如果您实际拥有类ter
的实例,则可以使用该名称调用该函数:
#在Person对象上调用“实例方法”
class Person:
def __init__(self, name): # Constructor
self.name = name
def sayHello(self): # Class method (requires `self` parameter)
print 'Hello, {0}'.format(self.name)
def main():
p = Person('Joe') # Instantiate `Person` class (calls constructor)
p.sayHello() # Call an "instance method" on Person object
如果你确定你想使用静态方法:
class Person:
def __init__(self, name): # Constructor
self.name = name
def sayHello(self): # Class method (requires `self` parameter)
print 'Hello, {0}'.format(self.name)
@staticmethod
def makePerson(name): # Static Method (note, no `self` parameter)
p = Person(name)
return p
@classmethod
def makePerson2(cls, name): # Class method. First parameter is class
p = cls(name) # Call constructor for that class
return p
def main():
p2 = Person.makePerson('Joe') # Call static "factory" method
p2.sayHello()
最后,尽管Python没有大括号/括号,但它对语法非常挑剔。如果您不打算声明方法的主体,则必须使用pass
keyword:
def foo():
pass # This function does nothing
答案 1 :(得分:1)
class ter:
def func1(self):
print 'I am func1'
def func2(self):
pass
class fg:
def gl1(self):
pass
def gl2(self):
ter_object=ter()
ter_object.func1()
这应打印I am func1
。
这里需要记住的是,除非调用静态方法