Sad*_*tam 52 python static-methods
我在该类中有一个类Person
和一个静态方法,名为call_person
:
class Person:
def call_person():
print "hello person"
Run Code Online (Sandbox Code Playgroud)
在python控制台中,我导入类Person并调用Person.call_person()
.但它给我的错误说'module' object has no attribute 'call_person'
.任何人都可以让我知道为什么我收到此错误?
mgi*_*son 111
你需要做一些事情:
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
Run Code Online (Sandbox Code Playgroud)
根据您的想法,类方法可能更合适:
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
Run Code Online (Sandbox Code Playgroud)
这里的区别在于,在第二个示例中,类本身作为方法的第一个参数传递(与实例是第一个参数的常规方法或不接收任何其他参数的static方法相对).
现在回答你的实际问题.我打赌你没有找到你的方法,因为你把课程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
Run Code Online (Sandbox Code Playgroud)
或者,您可能希望从模块Person中导入类Person:
from Person import Person
Person.call_person()
Run Code Online (Sandbox Code Playgroud)
对于什么是模块以及什么是类,这一切都有点令人困惑.通常,我尽量避免给出与它们所在模块同名的类.但是,datetime
由于标准库中的模块包含一个datetime
类,因此显然没有太过低估.
最后,值得指出的是,你并不需要一个类为这个简单的例子:
#Person.py
def call_person():
print "Hello person"
Run Code Online (Sandbox Code Playgroud)
现在在另一个文件中,导入它:
import Person
Person.call_person() #'Hello person'
Run Code Online (Sandbox Code Playgroud)
jam*_*lak 14
每个人都已经解释了为什么这不是一个静态的方法,但我会解释为什么你没有找到它.您正在寻找模块中的方法而不是类中的方法,所以这样的东西会正确找到它.
import person_module
person_module.Person.call_person() # Accessing the class from the module and then calling the method
Run Code Online (Sandbox Code Playgroud)
正如@DanielRoseman所说,您可能已经想到模块包含一个与Java相同的类,尽管在Python中并非如此.
小智 6
在 python 3.x 中,你可以声明一个静态方法如下:
class Person:
def call_person():
print "hello person"
Run Code Online (Sandbox Code Playgroud)
但是第一个参数为 self 的方法将被视为类方法:
def call_person(self):
print "hello person"
Run Code Online (Sandbox Code Playgroud)
在 python 2.x 中,必须@staticmethod
在静态方法之前使用 a :
class Person:
@staticmethod
def call_person():
print "hello person"
Run Code Online (Sandbox Code Playgroud)
您还可以将静态方法声明为:
class Person:
@staticmethod
def call_person(self):
print "hello person"
Run Code Online (Sandbox Code Playgroud)
那不是静态方法;尝试
class Person:
@staticmethod
def call_person():
print "hello person"
Run Code Online (Sandbox Code Playgroud)
请参阅此处了解更多信息。