你需要做如下事情:class Person(object): #always inherit from object. It's just a good idea...
@staticmethod
def call_person():
print "hello person"
#Calling static methods works on classes as well as instances of that class
Person.call_person() #calling on class
p = Person()
p.call_person() #calling on instance of class
根据您的需要,classmethod可能更合适:class Person(object):
@classmethod
def call_person(cls):
print "hello person",cls
p = Person().call_person() #using classmethod on instance
Person.call_person() #using classmethod on class
这里的区别在于,在第二个示例中,类本身作为第一个参数传递给方法(而不是将实例作为第一个参数的常规方法,或者不接收任何附加参数的staticmethod)。
现在回答你真正的问题。我打赌您没有找到您的方法,因为您已经将类Person放入模块Person.py。
然后:import Person #Person class is available as Person.Person
Person.Person.call_person() #this should work
Person.Person().call_person() #this should work as well
或者,您可能希望从模块人员中导入类人员:from Person import Person
Person.call_person()
对于什么是模块,什么是类,这些都有点混乱。通常,我会尽量避免给类赋予与它们所在模块相同的名称。然而,由于标准库中的datetime模块包含一个datetime类,这一点显然没有受到太多的重视。
最后,值得指出的是,对于这个简单的示例,您不需要一个类:#Person.py
def call_person():
print "Hello person"
现在在另一个文件中,导入它:import Person
Person.call_person() #'Hello person'