美文网首页魔术方法
python——装饰器&魔法方法

python——装饰器&魔法方法

作者: 小二哥很二 | 来源:发表于2019-07-26 14:26 被阅读0次

1、装饰器@classmethod

被@classmethod装饰的方法
1. 强制带个参数,cls,cls代表这个类本身
2. 不用实例化,和静态方法一样,直接 类().方法() 即可调用
3. cls是个位置参数,可随意换成其他词,如this
from ddt import ddt,data,unpack

class test():
    bar=1
    def fun1(self):
        print('foo')

    @classmethod
    def fun2(cls):
        print('fun2')
        print((cls.bar))
        cls().fun1()

test.fun2()

运行结果:
=>fun2
  1
  foo

**已知cls代表类本身,那么cls(123),就等价于A(123),调用init初始化,实例化为x
cls(123) 等价于 x = A(123)**
class test():
    def __init__(self,q):
        self.q=q

    @classmethod
    def fun(cls):
        return cls(123)
x=test.fun()
print(x.q)

运行结果:
=>123

2、call方法使用

call方法
普通的类定义的方法,由该类实例化的对象点( . )调用,
call方法调用形式 则是直接实例对象跟( )调用,即a( )形式调用

class Test():
    def __init__(self,size,x,y):
        self.x,self.y=x,y
        self.size=size
        print(size,x,y)
    def __call__(self,x,y):
        self.x,self.y=x,y
        print(x,y)
e=Test(1,2,3)  #创建实例化对象
e(4,5)  #直接实例调用
==>运行结果:
1 2 3
4 5

2、getattr函数使用
getattr() 函数用于返回一个对象属性值。
getattr(o,name,default)

tester.py
class Test:
    age = 10

    def __init__(self):
        self.name = 'Donald'

    @staticmethod    //静态方法
    def sex():
        return 'man'
========================================================
BasePage.py
from testFile import tester

case=getattr(tester.Test,'age')
case2=getattr(tester.Test,'sex')()
print(case)      ==>10
print(case2)     ==>man

3、__ str __使用
可以返回类属性并打印出来

class person():
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __str__(self):
        return '(Person:%s,%s)'%(self.name,self.age)
a=person('bob',12)
print(a)   ==>(Person:bob,12)
否则显示 ==>  <__main__.person object at 0x000001F09DD91588>

PS:觉得这篇文章有用的朋友,多多点赞打赏哦~!

相关文章

网友评论

    本文标题:python——装饰器&魔法方法

    本文链接:https://www.haomeiwen.com/subject/rcgrrctx.html