您需要执行以下操作:
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
根据您要执行的操作,类方法可能更合适:
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
区别在于,在第二个示例中,类本身作为第一个参数传递给方法(与实例作为第一个参数或不接收任何其他参数的静态方法的常规方法相反)。
现在回答您的实际问题。 我敢打赌,您找不到方法,因为您已将datetime类放入了模块datetime中。
然后:
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
或者,您可能要从Person模块中导入Person类:
from Person import Person
Person.call_person()
关于什么是模块和什么是类,这一切都令人困惑。 通常,我会尽量避免为类提供与它们所在的模块相同的名称。但是,由于标准库中的datetime模块包含datetime类,因此,显然不要忽略太多。
最后,值得指出的是,对于这个简单的示例,您不需要一个类:
#Person.py
def call_person():
print "Hello person"
现在在另一个文件中,将其导入:
import Person
Person.call_person() #'Hello person'