python 旧类中使用property特性的方法

在python中,我们可以拦截对象的所有特性访问。通过这种拦截的思路,我们可以在旧式类中实现property方法。

__getattribute__(self, name) #当特性name被访问时自动调用(只能在新式类中使用)
__getattr__(self, name) #当特性name被访问且对象没有相应的特性时被自动调用
__setattr__(self, name, value) #当试图给特性name赋值时会被自动调用
__delattr__(self, name) #当试图删除特性name时被自动调用

#*相比于使用property有点复杂,但是特殊方法用途很广

下面是举例:

class Demo5(object):
    def __init__(self):
        print("这是构造函数")
        self._value1 = None
        self._value2 = None

    def __setattr__(self, key, value):
        print("try to set the value of the  %s property" % (key,))
        if key == ‘newValue‘:
            self._value1, self._value2 = value
        else:
            print("the property key is not newValue, now create or set it through __dict__")
            self.__dict__[key] = value

    def __getattr__(self, item):
        print("try to get the value of %s " % (item,))
        if item == ‘newValue‘:
            return self._value1, self._value2
        else:
            print("the %s item is not exist" % (item,))
            #raise AttributeError

    def __delattr__(self, item):
        if item == ‘newValue‘:
            print("delete the value of newValue")
            del self._value1
            del self._value2
        else:
            print("delete other values ,the value name is %s" % item)

if __name__ == "__main__":
    testDemo = Demo5()
    print(testDemo.newValue)
    testDemo.newValue = "name","helloworld"
    print("print the value of property:", testDemo.newValue)
    print(testDemo.notExist)
    del testDemo.newValue

下面是结果:

这是构造函数
try to set the value of the  _value1 property
the property key is not newValue, now create or set it through __dict__
try to set the value of the  _value2 property
the property key is not newValue, now create or set it through __dict__
try to get the value of newValue
(None, None)
try to set the value of the  newValue property
try to set the value of the  _value1 property
the property key is not newValue, now create or set it through __dict__
try to set the value of the  _value2 property
the property key is not newValue, now create or set it through __dict__
try to get the value of newValue
(‘print the value of property:‘, (‘name‘, ‘helloworld‘))
try to get the value of notExist
the notExist item is not exist
None
delete the value of newValue
delete other values ,the value name is _value1
delete other values ,the value name is _value2

**其实,我们可以发现在使用__setatter__ , __getatter__,__delatter__这些接口时会对其他的值造成影响,因为这个是通用的必须调用的接口。

原文地址:https://www.cnblogs.com/zhangdewang/p/9072599.html

时间: 2024-08-24 20:56:45

python 旧类中使用property特性的方法的相关文章

转:python学习——类中为什么要定义__init__()方法

学习Python的类,一直不太理解为什么一定要定义init()方法,现在简要谈一下自己的理解吧. 1.不用init()方法定义类定义一个矩形的类,目的是求周长和面积. 1 class Rectangle(): 2 def getPeri(self,a,b): 3 return (a + b)*2 4 def getArea(self,a,b): 5 return a*b 6 7 rect = Rectangle() 8 print(rect.getPeri(3,4)) 9 print(rect.

类中为什么要定义__init__()方法

总结一下, 加上__init__()方法后,类才可以实例化,不加类就是个空壳,相当于一个方法集合 学习Python的类,一直不太理解为什么一定要定义init()方法,现在简要谈一下自己的理解吧. 1.不用init()方法定义类 定义一个矩形的类,目的是求周长和面积. class Rectangle(): def getPeri(self,a,b): return (a + b)*2 def getArea(self,a,b): return a*b rect = Rectangle() prin

NSMutableDictionary 类中增加键值对方法分析

在iOS中可变字典增加一个键值对的方法有setObject: forKey: 和setValue : forKey: .为了方便我们把这两个方法简称为方法A和方法B. B这个方法中其中的value值是不能为nil,否则程序会出项崩溃.而A方法中的这个value可以为nil,但是当这个value位nil时,系统会自动调用removeObjectforKey:这个方法.这样就把这个键值对删除掉了.B方法中的key值可以是任意类型的,但是这个类型必须要实现NSCopying协议.而A方法中它的key值

C#判断一个类中有无"指定名称"的方法

C#中可以通过反射分析元数据来解决这个问题,示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 using System; using System.Reflection; namespace Hello {     class Program     {  

scala中隐式转换之隐式转换调用类中本不存在的方法

/** * Created by root * Description : 隐式转换调用类中本不存在的方法 */ class Person(name : String){ def getPersonName = println("name = " + name) } object Type2Type{ implicit def type2(a : ImplicitTest2) = new Person("xiaoming") } class ImplicitTest

python 之用装饰器@property,把方法变成一个特性

# -*- coding: utf-8 -*- """ Created on Sun Nov 13 23:19:03 2016 @author: toby """ #知识点:用装饰器@property,把方法变成一个特性 class Province:     memo = 'One of China\'s 23 provinces' #静态字段          def __init__(self,name,capital,leadership

梳理:python—同一个类中的方法调用

为什么突然在此提到这个梳理问题呢? 因为在自己实践综合练习学过的知识时,突然觉得有些知识点的运用总是不成功,于是翻过课本进行回顾,总是觉得是对的,可是当再进一步思考"既然是对的,为什么在程序中总是不成功呢?",后来发现,自己理所当然的理解(忽略了细节知识),导致程序通不过,现在结合同一个类中的不同方法中的变量调用 VS 不同函数中的变量调用. 同一个类中的不同方法中的变量调用: class A(): def a_add_b(self): a=10 b=20 self.s =a+b se

python在类中使用__slot__属性

在类中定义__slot__属性来限制实例的属性字段,在创建大量对象的场合可以减少内存占用. 创建大量对象是内存占用对比: 类中不使用__slot__ class MySlot:def __init__(self, a, b, c): self.a = a self.b = b self.c = c @profile() def main(): myObj_list = list() for i in range(50000): myObj = MySlot(i, i, i) myObj_list

java反射之遍历类中所有内部类及属性方法

package com.zr.entity; /** * 仅用于测试类,从实际项目中抽出来的 * @author zr * */ public class Constant { /** * 参数校验枚举类 * @author zr * */ public static enum ResultObjectType { //成功 SUCC(0), //失败,异常 ERROR(1), //参数错误 PARAMERROR(2), //数据为空 NODATA(9); private Integer val