简体   繁体   English

是否有预定义的 python 描述符 class?

[英]Is there a pre-defined python descriptor class?

I want to create a class that has a whole lot of properties that for the most part will be just get and set.我想创建一个 class ,它有很多属性,大部分只是获取和设置。 Here is an example MyClass()这是一个示例 MyClass()

>>> class MyClass():
...     def getx(self): return self.__x
...     def setx(self, value): self.__x = value
...     def delx(self): del self.__x
...     x = property(getx, setx, delx, "I'm the 'x' property.")
...     y = property(getx, setx, delx, "I'm the 'y' property.")
...
>>> bar = MyClass()
>>> bar.x = 'jeff'
>>> bar.y = 3
>>> print(bar.x)
3
>>> print(bar.y)
3
>>>

Here the x and y properties are the same, so if I want x and y to be unique I will need a new getx/setx/delx for each one.这里的 x 和 y 属性是相同的,所以如果我希望 x 和 y 是唯一的,我将需要一个新的 getx/setx/delx 。

This example works better.这个例子效果更好。

>>> class MyClassBase():
...     def __init__(self, initval=None):
...         self.val = initval
...     def __get__(self, obj, objtype):
...         return self.val
...     def __set__(self, obj, val):
...         self.val = val
...
>>> class MyClassFinal():
...     x = MyClassBase(1)
...     y = MyClassBase('xyzzy')
...
>>> foo = MyClassFinal()
>>> foo.x = 2
>>> print(foo.x)
2
>>> print(foo.y)
xyzzy
>>>

I think MyClassBase() is what they call (or is the equivalent of) a descriptor class.我认为 MyClassBase() 是他们所说的(或等同于)描述符 class。 Now the properties x, y (and any others I choose to add to MyClassFinal() ) are independent.现在属性 x、y(以及我选择添加到 MyClassFinal() 的任何其他属性)是独立的。

It seems odd I need to create MyClassBase() on my own.我需要自己创建 MyClassBase() 似乎很奇怪。 Isn't this (or something equivalent) already defined somewhere so I don't need to create my own?这个(或等价的)不是已经在某个地方定义了,所以我不需要创建我自己的吗?

I am also open to a different example of how to create a class with a lot of properties and a minimum of code.我也对如何创建具有大量属性和最少代码的 class 的不同示例持开放态度。

Ahhh!啊! I'm making things way too complicated.我把事情弄得太复杂了。 Apparently all I need to do is this:显然我需要做的就是:

>>> class MyClassSimple:
...     x = 1
...     y = 'blue'
...     def __str__(self):
...         return f'{self.x}, {self.y}'
...
>>> zot = MyClassSimple()
>>> print(zot)
1, blue
>>> zot.x = 'red'
>>> zot.y = 3
>>> print(zot)
red, 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM