首页 > 编程语言 > 详细

python- 属性访问

时间:2019-03-05 21:31:43      阅读:177      评论:0      收藏:0      [点我收藏+]

getattr()

  Docstring: getattr(object, name[, default]) -> value Get a named attribute from an object;

   getattr(x, ‘y‘) is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn‘t exist; without it, an exception is raised in that case.

setattr()

  Signature: setattr(obj, name, value, /)

  Docstring: Sets the named attribute on the given object to the specified value.

  setattr(x, ‘y‘, v) is equivalent to ``x.y = v‘‘

delattr()

  Signature: delattr(obj, name, /)

  Docstring: Deletes the named attribute from the given object.

  delattr(x, ‘y‘) is equivalent to ``del x.y‘‘

避免内置函数的递归调用:

 1 class rectan():
 2     def __init__(self, x, y):
 3         self.x = x
 4         self.y = y
 5         
 6     def __setattr__(self, name, value):
 7         print(setattr)
 8         if name == square:
 9             self.x = vlaue
10             self.y = value
11             
12 #             super().__setattr__(‘x‘, value)
13 #             super().__setattr__(‘y‘, value)
14         else:
15 #             self.name = value
16             super().__setattr__(name, value)

如使用第15 行进行赋值操作会出现递归现象,这是由于,在实例化对象时,调用了 __init__()方法, 而该方法中进行了 属性设置操作,对于该对象来说就需要调用该对象的__setattr__()方法进行属性设置,而15行的属性设置仍然需要调用该对象本身的__setattr__()方法,从而产生递归调用,解决办法是使用 16行代码,使用其他对象的__setattr__()方法,由于父类与该对象有直接关系,因此调用父类的方法。

 

属性名以字符串的方式传入。

__getattr__(self, name):定义当试图访问一个不存在的属性名时的行为。(基类object 中无该方法)

__getattribute__(self, name):定义该类的属性被访问时的行为。 属性被访问时先访问的方法

__setattr__(self, name, value):定义一个属性被设置时的行为

__delattr__(self, name): 定义一个属性被删除时的行为

 1 class test():
 2     def __setattr__(self, name, value):
 3         print(setattr)
 4         super().__setattr__(name, value)
 5         
 6     def __getattr__(self,name):
 7         print(setattr)
 8 
 9     
10     def __getattribute__(self, name):
11         print(getattribute)
12         return super().__getattribute__(name)
13     
14     def __delattr__(self, name):
15         print(delsttr)
16         super().__delattr__(name)
17         
18 t = test()
19 setattr(t,x,10)
20 getattr(t,x)
21 delattr(t,x)
22 getattr(t,x)
23 
24 ################################
25 
26 setattr
27 getattribute
28 delsttr
29 getattribute
30 setatt

python- 属性访问

原文:https://www.cnblogs.com/JYNNO1/p/10479738.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!