【问题标题】:Cython module propertyCython 模块属性
【发布时间】:2021-10-14 23:45:13
【问题描述】:

在 Cython 中,您可以为类属性定义 getter 和 setter 函数:

cdef class module
  property a:
    def __get__(self):
      cdef int a
      get_a(&a)
      return a
    def __set__(self, int a):
      set_a(&a)

有没有办法在模块级别定义 getter 和 setter?例如,语法可能看起来像这样。

@module_property
def a():
  pass
  
@a.setter
def a(int new_a):
  set_a(&new_a)
  
@a.getter
def a():
  cdef int a_copy
  get_a(&a_copy)
  return a_copy

【问题讨论】:

  • 可能不会。为什么不直接使用定义所需属性的类的全局实例?
  • 好点。效果很好
  • 原则上,将 c 类型的模块级变量暴露给 Python 会很有帮助。虽然我认为目前不支持它
  • @Brian 与 C 语言中的 Python 模块类似的是namespace,可以在命名空间中使用变量吗?

标签: python cython python-c-api cythonize


【解决方案1】:

正如@Brian 指出的那样,类的全局实例效果很好。所以它可能看起来像:

cdef class module: 
  property a:
    def __get__(self):
      cdef int a_copy
      get_a(&a_copy)
      return a
    def __set__(self, int new_a):
      set_a(&new_a)
      
module_instance = module()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 2021-12-24
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2017-10-18
    相关资源
    最近更新 更多