内容简介:我们在访问类的字段时,还有一些过滤的条件,类似于前端语言比如vue Js、anjularJs中过滤器的概念。在3.0以前可以使用比如,__setattr__,__getattr__的方法进行属性的过滤。在3.0以后我们如果对某些字段需要过滤访问,也可以使用这些函数。输出Python中静态方法和类的成员方法,使用不太广泛,可以了解一下。一般还是使用函数和绑定方法。
我们在访问类的字段时,还有一些过滤的条件,类似于前端语言比如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
以上所述就是小编给大家介绍的《少说话多写代码之Python学习050——类的成员(静态方法,类成员方法,getattr,setattr)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 如何测试只修改私有类成员变量的void方法?
- Minion:让非DAO成员参与DAO事务的实现方法 | 火星号精选
- 少说话多写代码之Python学习054——类的成员(生成器的方法和模拟生成器))
- C++指针与成员
- C++实现成员函数检查
- 常对象与常成员函数
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming Computer Vision with Python
Jan Erik Solem / O'Reilly Media / 2012-6-22 / USD 39.99
If you want a basic understanding of computer vision's underlying theory and algorithms, this hands-on introduction is the ideal place to start. As a student, researcher, hacker, or enthusiast, you'll......一起来看看 《Programming Computer Vision with Python》 这本书的介绍吧!