在python中调用静态方法 [英] Calling static method in python

查看:23
本文介绍了在python中调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Person 类和一个名为 call_person 的静态方法:

I have a class Person and a static method in that class called call_person:

class Person:
    def call_person():
        print "hello person"

在 python 控制台中,我导入类 Person 并调用 Person.call_person().但它给我的错误是 'module' 对象没有属性 'call_person'.谁能告诉我为什么我会收到这个错误?

In the python console I import the class Person and call Person.call_person(). But it is giving me error that says 'module' object has no attribute 'call_person'. Can anyone please let me know why I am getting this error?

推荐答案

您需要执行以下操作:

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

根据您想要做什么,类方法可能更合适:

Depending on what you want to do, a classmethod might be more appropriate:

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

这里的区别在于,在第二个示例中,类本身作为第一个参数传递给方法(而不是常规方法,其中实例是第一个参数,或者不接收任何额外参数的静态方法)参数).

The difference here is that in the second example, the class itself is passed as the first argument to the method (as opposed to a regular method where the instance is the first argument, or a staticmethod which doesn't receive any additional arguments).

现在回答您的实际问题.我敢打赌你没有找到你的方法,因为你已经把 Person 类放到了一个模块 Person.py 中.

Now to answer your actual question. I'm betting that you aren't finding your method because you have put the class Person into a module 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:

Alternatively, you might want to import the class Person from the module Person:

from Person import Person
Person.call_person()

对于什么是模块和什么是类,这一切都会让人有点困惑.通常,我尽量避免给类赋予与它们所在的模块相同的名称.然而,这显然没有被低估,因为标准库中的 datetime 模块包含一个 日期时间类.

This all gets a little confusing as to what is a module and what is a class. Typically, I try to avoid giving classes the same name as the module that they live in. However, this is apparently not looked down on too much as the datetime module in the standard library contains a datetime class.

最后,值得指出的是,对于这个简单的例子,你不需要一个类:

Finally, it is worth pointing out that you don't need a class for this simple example:

# Person.py
def call_person():
    print "Hello person"

现在在另一个文件中,导入它:

Now in another file, import it:

import Person
Person.call_person() # 'Hello person'

这篇关于在python中调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆