【问题标题】:Difference between class and instance methods类方法和实例方法的区别
【发布时间】:2013-06-12 15:32:18
【问题描述】:

我正在阅读PEP 8 (style guide),我注意到它建议使用 self 作为实例方法中的第一个参数,但 cls 作为类方法中的第一个参数。

我已经使用并编写了一些类,但我从未遇到过类方法(嗯,一种将 cls 作为参数传递的方法)。有哪些例子?

【问题讨论】:

  • 恕我直言,这不是重复的。虽然本质上相似,但这篇文章侧重于 Python 解决方案,而其他文章则使用对 java 的引用并侧重于理论。 a) 不是每个人都知道 java 和 b) 有时通过示例应用比简洁的理论解释更好。我个人认为“链接的答案”不是答案。这里发布的答案是。在协同工作时,可能会产生更好的理解,缺乏明确的方向并造成进一步的混乱。

标签: python


【解决方案1】:

实例方法

创建实例方法时,第一个参数总是self。 您可以随意命名,但含义始终相同,您应该使用self,因为这是命名约定。 self(通常)在调用实例方法时被隐藏传递;它代表调用方法的实例。

这是一个名为 Inst 的类的示例,它有一个名为 introduce() 的实例方法:

class Inst:

    def __init__(self, name):
        self.name = name

    def introduce(self):
        print("Hello, I am %s, and my name is " %(self, self.name))

现在要调用这个方法,我们首先需要创建我们类的一个实例。 一旦我们有了一个实例,我们就可以在它上面调用introduce(),实例会自动传递为self

myinst = Inst("Test Instance")
otherinst = Inst("An other instance")
myinst.introduce()
# outputs: Hello, I am <Inst object at x>, and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am <Inst object at y>, and my name is An other instance

如您所见,我们没有传递参数self,它是通过句号运算符隐藏传递的;我们调用Inst类的实例方法introduce,参数为myinstotherinst。 这意味着我们可以调用Inst.introduce(myinst) 并得到完全相同的结果。


类方法

类方法的思想与实例方法非常相似,唯一的区别是我们现在将类本身作为第一个参数传递,而不是将实例作为第一个参数隐藏传递。

class Cls:

    @classmethod
    def introduce(cls):
        print("Hello, I am %s!" %cls)

由于我们只向方法传递一个类,因此不涉及实例。 这意味着我们根本不需要实例,我们调用类方法就好像它是一个静态函数:

 Cls.introduce() # same as Cls.introduce(Cls)
 # outputs: Hello, I am <class 'Cls'>

注意Cls 再次被隐藏传递,所以我们也可以说Cls.introduce(Inst) 并得到输出"Hello, I am &lt;class 'Inst'&gt;。 这在我们从 Cls 继承类时特别有用:

class SubCls(Cls):
    pass

SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>

【讨论】:

  • 你不是说第一个例子中的 x.p() 而不是 print(x) 吗?
  • @amo-ej1 不错,已修复。
【解决方案2】:

简单地说,实例方法是在类内部定义的函数。它随类的不同实例而变化。 示例:

class Dog:
    def __init__(self, sound):
        self.sound = sound
    def bark(self):
        return f"The dog makes the sound: {self.sound}"

而类方法与 bark() 方法不同,它应用于类的所有实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2010-11-06
    • 2012-08-06
    • 2012-08-13
    • 2015-12-11
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多