我在该类中有一个类Person
和一个静态方法,称为call_person
:
class Person:
def call_person():
print "hello person"
在 python 控制台中,我导入类 Person 并调用Person.call_person()
. 但它给了我错误说'module' object has no attribute 'call_person'
。谁能告诉我为什么我会收到这个错误?
我在该类中有一个类Person
和一个静态方法,称为call_person
:
class Person:
def call_person():
print "hello person"
在 python 控制台中,我导入类 Person 并调用Person.call_person()
. 但它给了我错误说'module' object has no attribute 'call_person'
。谁能告诉我为什么我会收到这个错误?
您需要执行以下操作:
class Person:
@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:
@classmethod
def call_person(cls):
print "hello person",cls
p = Person().call_person() # using classmethod on instance
Person.call_person() # using classmethod on class
此处的区别在于,在第二个示例中,类本身作为第一个参数传递给方法(与以实例为第一个参数的常规方法或不接收任何附加参数的静态方法相反)。
现在回答你的实际问题。我打赌你没有找到你的方法,因为你已经把类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
或者,您可能希望从模块 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'
每个人都已经解释了为什么这不是静态方法,但我会解释为什么你没有找到它。您正在模块中而不是类中寻找方法,因此类似这样的方法会正确找到它。
import person_module
person_module.Person.call_person() # Accessing the class from the module and then calling the method
同样正如@DanielRoseman 所说,您可能已经想象模块包含一个与Java 同名的类,尽管在Python 中并非如此。
在 python 3.x 中,您可以声明一个静态方法,如下所示:
class Person:
def call_person():
print "hello person"
但是第一个参数为 self 的方法将被视为类方法:
def call_person(self):
print "hello person"
在 python 2.x 中,必须@staticmethod
在静态方法之前使用 a:
class Person:
@staticmethod
def call_person():
print "hello person"
您还可以将静态方法声明为:
class Person:
@staticmethod
def call_person(self):
print "hello person"
您需要添加装饰器类方法。