python 类方法classmethod

2019-12-13 15:08:24 浏览数 (1)

为了实现多个构造器,你需要使用到类方法。例如:

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 12px; white-space: pre; margin: 0px; padding: 12px; display: block; overflow: auto; line-height: 1.4;">import time

class Date: """方法一:使用类方法""" # Primary constructor def init(self, year, month, day): self.year = year self.month = month self.day = day

代码语言:javascript复制
# Alternate constructor
@classmethod
def today(cls):
    t = time.localtime()
    return cls(t.tm_year, t.tm_mon, t.tm_mday)

</pre>

直接调用类方法即可,下面是使用示例:

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 12px; white-space: pre; margin: 0px; padding: 12px; display: block; overflow: auto; line-height: 1.4;">a = Date(2012, 12, 21) # Primary b = Date.today() # Alternate </pre>

讨论

类方法的一个主要用途就是定义多个构造器。它接受一个 class 作为第一个参数(cls)。 你应该注意到了这个类被用来创建并返回最终的实例。在继承时也能工作的很好:

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", Courier, monospace; font-size: 12px; white-space: pre; margin: 0px; padding: 12px; display: block; overflow: auto; line-height: 1.4;">class NewDate(Date): pass

c = Date.today() # Creates an instance of Date (cls=Date) d = NewDate.today() # Creates an instance of NewDate (cls=NewDate)</pre>

0 人点赞