小编Sto*_*ker的帖子

如何在Python中定义类字段作为类的实例?

我想在类的命名空间中获取特定的类实例。在 C# 中,这看起来像这样:

public struct Foo
{
    public readonly static Bar = new Foo();
}
Run Code Online (Sandbox Code Playgroud)

我唯一的想法是在类定义之后分配一个实例(monkeypatch):

public struct Foo
{
    public readonly static Bar = new Foo();
}
Run Code Online (Sandbox Code Playgroud)

但我想在类定义中提供实例,如下所示:

class Foo:
    def __init__(self, spam):
        self.spam = spam
Foo.bar = Foo(42)
Run Code Online (Sandbox Code Playgroud)

以及这样的界面:

class Foo:
    ...
    bar = Foo(42)
Run Code Online (Sandbox Code Playgroud)

定义中的最后一行给出语法错误,因为 Foo 尚未定义。除了monkeypatching类之外,还有什么方法可以克服这个限制吗?

c# python metaprogramming

4
推荐指数
1
解决办法
852
查看次数

测试使用enquo()作为NULL参数的函数

我有一个创建数据框的函数,但是会在过程中更改名称。我正在尝试使用dplyr quosures处理空列名称。我的测试套件如下所示:

dataframe <- data_frame(
  a = 1:5,
  b = 6:10
)

my_fun <- function(df, col_name, new_var_name = NULL) {
  target <- enquo(col_name)

  c <- df %>% pull(!!target) * 3 # here may be more complex calculations

  # handling NULL name
  if (is.null(new_var_name)) {
    new_name <- quo(default_name)
  } else{
    new_name <- enquo(new_name)
  }

  data_frame(
    abc = df %>% pull(!!target),
    !!quo_name(new_name) := c
  )
}
Run Code Online (Sandbox Code Playgroud)

如果我这样调用函数:

my_fun(dataframe, a)
Run Code Online (Sandbox Code Playgroud)

我得到预期的默认名称:

# A tibble: 5 x 2
    abc default_name
  <int>        <dbl>
1     1 …
Run Code Online (Sandbox Code Playgroud)

r dplyr

2
推荐指数
1
解决办法
332
查看次数

标签 统计

c# ×1

dplyr ×1

metaprogramming ×1

python ×1

r ×1