Python描述符

当一个类的某一个属性也为类的时候,(对象)调用该属性会调用该属性的__getter__()方法,
自动调用的,类似于创建对象时会自动调用__init__()方法一样。
例子:
class Twenty:
def init(self, name, value):
self.name = name
self.value = value
print(“object”, self.name, “is created”)
def get(self, obj, objtype):
print(“value is:”)
return self.value

class TestClass:
def init(self):
print(“TestClass Obj is created”)
testAttribute = Twenty(“describer”, 20)

输出:
object describer is created

可见当一个类中的某个属性为另一个类时,如A类的某个属性Bvariable为B类,不管有没有创建对象,都会调用B类的__init__方法。

继续搞事情,添加几段代码如下:
class Twenty:
def init(self, name, value):
self.name = name
self.value = value
print(“object”, self.name, “is created”)
def get(self, obj, objtype):
print(“value is:”)
return self.value

class TestClass:
def init(self):
print(“TestClass Obj is created”)
testAttribute = Twenty(“describer”, 20)

print(“0------------0”)
TestObj = TestClass()

输出:
object describer is created
0------------0
TestClass Obj is created

可见当A类创建对象时,只会调用A类的__init__方法,而不会调用B类的__init__方法,即使A类包含B类。

继续搞事情,添加代码如下:
class Twenty:
def init(self, name, value):
self.name = name
self.value = value
print(“object”, self.name, “is created”)
def get(self, obj, objtype):
print(“value is:”)
return self.value

class TestClass:
def init(self):
print(“TestClass Obj is created”)
testAttribute = Twenty(“describer”, 20)

print(“0------------0”)
TestObj = TestClass()
print(“1------------1”)
TestObj.testAttribute

输出:
object describer is created
0------------0
TestClass Obj is created
1------------1
value is:

可见当A类创建的对象,引用属性Bvariable时会调用B类的__get__方法,这个时隐式的,而不需要使用诸如Aobj.Bvariable.get()之类的表达式,而且时自动调用,不得不调用。

继续搞事情,添加代码如下:
class Twenty:
def init(self, name, value):
self.name = name
self.value = value
print(“object”, self.name, “is created”)
def get(self, obj, objtype):
print(“value is:”)
return self.value

class TestClass:
def init(self):
print(“TestClass Obj is created”)
testAttribute = Twenty(“describer”, 20)

print(“0------------0”)
TestObj = TestClass()
print(“1------------1”)
TestObj.testAttribute
print(“2------------2”)
num = 5
num = TestObj.testAttribute
print(num, ’ ', type(num), ’ ',type(TestObj), ’ ', type(TestClass), ’ ', type(Twenty(“aa”, 20)))

输出:
object describer is created
0------------0
TestClass Obj is created
1------------1
value is:
2------------2
value is:
20 <class ‘int’> <class ‘main.TestClass’> <class ‘type’> <class ‘main.Twenty’>

此时程序员可能仅仅想获取返回值20,但是很遗憾,get__方法原本不动的将其内容输出,但其类型为返回值类型int。对象的类型为__main.+ ‘类名’,类的类型为type。

有了__get__方法后,下面例子中A类的属性没法被索引,注释掉的代码(最后三行)都会带来异常
class A:
A1 = 1
A2 = 2
def init(self):
self.a1 = 3
def get(self, tt1, tt2):
return self.a1
print(“dummy”)

class B:
B1 = A()

Bobj = B()

print(A.A1)
print(B.B1)

print(B.B1.A2)

print(Bobj.B1.A2)

print(Bobj.B1.a1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值