少说话多写代码之Python学习050——类的成员(静态方法,类成员方法,getattr,setattr)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yysyangyangyangshan/article/details/84504401

我们在访问类的字段时,还有一些过滤的条件,类似于前端语言比如vue Js、anjularJs中过滤器的概念。在3.0以前可以使用比如,__setattr__,__getattr__的方法进行属性的过滤。在3.0以后我们如果对某些字段需要过滤访问,也可以使用这些函数。

class Rectangle2:
    def __init__(self):
        self.width=0
        self.height=0

    def __setattr__(self, key, value):
        if key=='size':
            self.width,self.height=value
        else:
            self.__dict__[key]=value

    def __getattr__(self, name):
        if name=='size':
            return  self.width,self.height
        else:
            raise AttributeError

r=Rectangle2()
r.__setattr__('no',(100,61.8))
print(r.width,r.height)

r.__setattr__('size',(100,61.8))
print(r.width,r.height)

#r.__getattr__('no')
print(r.__getattr__('size'))

输出

0 0
100 61.8
(100, 61.8)

Python中静态方法和类的成员方法,使用不太广泛,可以了解一下。一般还是使用函数和绑定方法。

_metaclass_ =type
class MyClass:
    @staticmethod
    def smeth():
        print('静态方法')

    @classmethod
    def cmeth(cls):
        print('类的方法',cls)
MyClass.smeth()
MyClass.cmeth()

输出

静态方法
类的方法 <class '__main__.MyClass'>

工程代码下载:https://download.csdn.net/download/yysyangyangyangshan/10806872

猜你喜欢

转载自blog.csdn.net/yysyangyangyangshan/article/details/84504401
今日推荐