思科DevNet

python中常用的内置装饰器

2019-05-23  本文已影响0人  LittleBear_6c91

@property
使调用类中的方法像引用类中的字段属性一样。被修饰的特性方法,内部可以实现处理逻辑,但对外提供统一的调用方式。遵循了统一访问的原则。

示例:

coding: utf-8

class TestClass:
name = "test"

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

@property
def sayHello(self):
    print "hello", self.name

cls = TestClass("felix")
print "通过实例引用属性"
print cls.name
print "像引用属性一样调用@property修饰的方法"
cls.sayHello
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
输出结果:

通过实例引用属性
felix
像引用属性一样调用@property修饰的方法
hello felix
1
2
3
4
此外,@property可以用来实现类似与Java中set和get方法

@staticmethod
将类中的方法装饰为静态方法,即类不需要创建实例的情况下,可以通过类名直接引用。到达将函数功能与实例解绑的效果。

示例:

coding: utf-8

class TestClass:
name = "test"

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

@staticmethod
def fun(self, x, y):
    return  x + y

cls = TestClass("felix")
print "通过实例引用方法"
print cls.fun(None, 2, 3) # 参数个数必须与定义中的个数保持一致,否则报错

print "类名直接引用静态方法"
print TestClass.fun(None, 2, 3) # 参数个数必须与定义中的个数保持一致,否则报错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
输出结果:

通过实例引用方法
5
类名直接引用静态方法
5
1
2
3
4
@classmethod
类方法的第一个参数是一个类,是将类本身作为操作的方法。类方法被哪个类调用,就传入哪个类作为第一个参数进行操作。

实例:

coding: utf-8

class Car(object):
car = "audi"

@classmethod
def value(self, category): # 可定义多个参数,但第一个参数为类本身
    print "%s car of %s" % (category, self.car)

class BMW(Car):
car = "BMW"

class Benz(Car):
car = "Benz"

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

print "通过类名直接调用"
Benz.value("SUV")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
输出结果:

通过实例调用
Normal car of BMW
通过类名直接调用
SUV car of Benz
注意,静态方法和类方法是为类操作准备的。虽然通过实例也能调用,但是不建议。

上一篇 下一篇

猜你喜欢

热点阅读