Python类方法
时间:2020-02-23 14:42:31 来源:igfitidea点击:
Python类方法是为python类定义函数的方法。
Python类方法
在有关Python的这篇文章中,我们将看到如何定义和使用类方法。
我们将看到创建类方法并在程序中调用它们的方法。
Python中的方法类型
在Python中,可以在程序中创建两种类型的函数。
他们是:
- 静态方法
- 类方法
在本程序中,我们将重点介绍类方法。
制作python类方法
类方法是只能用Object的实例调用的方法。
这些方法通常定义对象的行为并修改对象的属性或者实例变量。
有两种方法可以在Python中创建类方法:
- 使用classmethod(function)
- 使用@classmethod注释
使用classmethod()
看起来不是Python风格的,因此,在较新的Python版本中,我们可以使用@classmethod批注装饰器来制作类方法。
提供样板
在本节中,我们将尝试建立对类方法的理解。
这是一个示例程序,以开始:
class DateTime(object): def __init__(self, day=10, month=10, year=2000): self.day = day self.month = month self.year = year
这只是一个简单的类定义。
我们将以此为基础。
我们包含了一个__init__函数来初始化该类的对象实例。
包括类方法
现在,我们将在最后一部分中增强样板代码,并其中包括一个类方法,该方法可以将日期作为" String"接收并返回一个实际的" Date"实例。
让我们看一下代码片段:
@classmethod def from_string(cls, string_date): day, month, year = map(int, string_date.split('-')) myDate = cls(day, month, year) return myDate
注意,由于该方法将类作为其引用的原因,该方法也将用作该类的构造函数。
而且,它实际上是从字符串构造类实例。
让我们看一下如何使用此构造函数的代码片段:
dateObj = DateTime.from_string('20-05-1994')
它与静态方法有何不同?
静态方法属于一个类,而不是该类的特定实例。
这是我们定义的DateTime
类的示例静态方法:
@staticmethod def is_valid_date(date_as_string): day, month, year = map(int, date_as_string.split('-')) return day <= 31 and month <= 12 and year <= 3999
可以像这样使用:
is_valid_date = Date.is_date_valid('20-05-1994')
其中我们对类的任何实例都不做任何事情,只是检查是否有适当的东西可以转换为该类的实例。
我们完整的类代码如下:
class DateTime(object): def __init__(self, day=10, month=10, year=2000): self.day = day self.month = month self.year = year @classmethod def from_string(cls, string_date): day, month, year = map(int, string_date.split('-')) myDate = cls(day, month, year) return myDate @staticmethod def is_valid_date(date_as_string): day, month, year = map(int, date_as_string.split('-')) return day <= 31 and month <= 12 and year <= 3999 dateObj = DateTime.from_string('20-05-1994') is_valid_date = DateTime.is_valid_date('20-05-1994') print(is_valid_date)