python内置哪些装饰器_Python内置装饰器

1、staticmethod()

a)描述

原文:

staticmethod(function) -> method

Convert a function to be a static method.

A static method does not receive an implicit first argument.

To declare a static method, use this idiom:

class C:

@staticmethod

def f(arg1, arg2, ...):

...

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++.

For a more advanced concept, see the classmethod builtin.

中文:

将函数转换为静态方法。

静态方法不接收隐式的第一个参数。

要声明一个静态方法,请使用以下习语:

class C:

@staticmethod

def f(arg1, arg2, ...):

...

它可以在类(e.g. C.f())上调用,也可以在实例上调用(e.g. C().f())。除了类之外,实例将被忽略。

Python中的静态方法类似于Java或C++中的方法。

有关更高级的概念,请参见classmethod builtin。

诠释:

staticmethod装饰器的功能是去除类的方法默认第一个参数是类的实例,使得该方法成为一个普通的函数,staticmethod是一个类,属于类装饰器。

b)实例

class TestClass:

name = "Test"

def __init__(self, name):

self.name = name

@staticmethod

def fun(x, y): # 不再传递self

return x + y

cls = TestClass("Kevin")

print("通过实例引用方法")

print(cls.fun(2, 3)) # 参数个数必须与定义中的个数保持一致,否则报错

print("类名直接引用静态方法")

print(TestClass.fun(2, 3)) # 参数个数必须与定义中的个数保持一致,否则报错

运行结果:

通过实例引用方法

5

类名直接引用静态方法

5

2、classmethod()

a)描述

原文:

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance.

To declare a class method, use this idiom:

class C:

@classmethod

def f(cls, arg1, arg2, ...):

...

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.

If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods.

If you want those, see the staticmethod builtin.

中文:

classmethod(function) -> method

将函数转换为类方法。

类方法接收类作为隐式的第一个参数,就像实例方法接收实例一样。

要声明类方法,请使用以下习语:

class C:

@classmethod

def f(cls, arg1, arg2, ...):

...

它可以在类(e.g. C.f())上调用,也可以在实例(e.g. C().f())上调用。除了类之外,实例将被忽略。

如果为派生类调用类方法,则将派生类对象作为隐含的第一个参数传递。

类方法与C++或Java静态方法不同。

如果您想要这些,请参阅staticmethod builtin。

诠释:

classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

b)实例

class Car(object):

car = "audi"

@classmethod

def value(cls, category): # 可定义多个参数,但第一个参数为类本身

print("%s car of %s" % (category, cls.car))

class BMW(Car):

car = "BMW"

class Benz(Car):

car = "Benz"

print("通过实例调用")

baoma = BMW()

baoma.value("Normal") # 由于第一个参数为类本身,调用时传入的参数对应的时category

print("通过类名直接调用")

Benz.value("SUV")

运行结果:

通过实例调用

Normal car of BMW

通过类名直接调用

SUV car of Benz

3、property()

a)描述

原文:

classmethod(function) -> method

Convert a function to be a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance.

To declare a class method, use this idiom:

class C:

@classmethod

def f(cls, arg1, arg2, ...):

...

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.

If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods.

If you want those, see the staticmethod builtin.

中文:

classmethod(function) -> method

将函数转换为类方法。

类方法接收类作为隐式的第一个参数,就像实例方法接收实例一样。

要声明类方法,请使用以下习语:

class C:

@classmethod

def f(cls, arg1, arg2, ...):

...

它可以在类(e.g. C.f())上调用,也可以在实例(e.g. C().f())上调用。除了类之外,实例将被忽略。

如果为派生类调用类方法,则将派生类对象作为隐含的第一个参数传递。

类方法与C++或Java静态方法不同。

如果您想要这些,请参阅staticmethod builtin。

诠释:

对于一个类的属性,python的访问是没有限制的,但有时候我们需要对属性的访问加以限制,property装饰器就是干这个的。

property是一个类,它有三个方法,deleter,setter,getter,有两种使用方式。

一个函数被property装饰后返回的是property对象,只有fget参数的函数可以被property,因为装饰器只接受一个参数;另外的属性设置和删除需要直观调用响应的方法。

b)语法

property() 方法的语法: class property([fget[, fset[, fdel[, doc]]]])

c)参数

fget -- 获取属性值的函数

fset -- 设置属性值的函数

fdel -- 删除属性值函数

doc -- 属性描述信息

d)返回值

返回新式类属性。

e)实例

实例01:

class Person():

_num_ear = 2

def __init__(self):

self._name = 'Kevin'

self.age = 20

def get_name(self):

print('get name')

return self._name

def set_name(self, name):

print('set name')

self._name = name

def delete_name(self):

print('del name')

del self._name

name = property(get_name, set_name, delete_name, doc='name of person')

if __name__ == '__main__':

p = Person()

print(p.name) # 会调用get_name

p.name = 'Key' # 会调用set_name

print(p.name)

del p.name # 会调用delete_name

运行结果:

get name

Kevin

set name

get name

Key

del name

实例02:

class Person():

_num_ear = 2

def __init__(self):

self._name = 'Kevin'

self.age = 20

@property

def name(self):

return self._name

@name.setter

def name(self, name):

print('set name')

self._name = name

@name.deleter

def name(self):

print('del name')

del self._name

if __name__ == '__main__':

p = Person()

print(p.name)

p.name = 'Key'

print(p.name)

del p.name

运行结果:

Kevin

set name

Key

del name

4、abstractmethod()

a)描述

原文:

A decorator indicating abstract methods.

Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden.

The abstract methods can be called using any of the normal 'super' call mechanisms. abstractmethod() may be used to declare abstract methods for properties and descriptors.

Usage:

class C(metaclass=ABCMeta):

@abstractmethod

def my_abstract_method(self, ...):

...

中文:

一个指示抽象方法的装饰器。

要求元类是ABCMeta或从ABCMeta派生。除非所有抽象方法都被覆盖,否则不能实例化从ABCMeta派生的元类。

可以使用任何普通的“super”调用机制来调用抽象方法。abstractmethod()可用于声明属性和描述符的抽象方法。

用法:

class C(metaclass=ABCMeta):

@abstractmethod

def my_abstract_method(self, ...):

...

诠释:

一个类中的任何方法被abstractmethod装饰后,这个类不能实例化并且子类必须实现被abstractmethod装饰的方法。

如果需要定义一个类是抽象类,那么它需要继承ABCMeta而不是object,这样abstractmethod装饰器才会起作用。其起作用的原理是将一个方法的__isabstractmethod__属性设置为True,这样解释器就会检查子类是否实现了抽象方法。

b)实例

from abc import abstractmethod,ABCMeta

class Animal(metaclass=ABCMeta):

@abstractmethod

def eat(self):

pass

class Person(Animal):

_num_ear = 2

def eat(self):

print('eat thing')

@classmethod

def go(cls):

print(cls._num_ear)

print('go')

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值