如何动态生成属性?

时间:2018-10-13 18:50:13

标签: python object attributes python-2.x

我正在使用以下python代码:

df <- data.frame ("col1" = c("red|",
                             "blue| , red|", 
                             "blue| , red| , yellow|"), 
                  "col2" = c("green",
                             "yellow , blue",
                             "black , red , blue"),
                  stringsAsFactors = F)
parts1 <- strsplit(df$col1, ' , ')
parts2 <- strsplit(df$col2, ' , ')
# join parts from two columns
n <- dim(df)[1]
df$col3 <- lapply(1:n, function(i) paste0(parts1[[i]], parts2[[i]])) 
# join joined parts to a single string per row
df$col3 <- lapply(col3, function(x) paste(x, collapse = ' , '))
df

                    col1               col2                               col3
1                   red|              green                          red|green
2           blue| , red|      yellow , blue             blue|yellow , red|blue
3 blue| , red| , yellow| black , red , blue blue|black , red|red , yellow|blue

最后一部分抛出以下错误:

class A(object):
   def __getattr__(self, name):
       print "__getattr__ : %s" % name
       setattr(self, name, A())
       print self.__dict__
       print getattr(self, name)

 x = A()
 x.a = 1 .  # Works fine.
 print x.a

 x.b.c = 2 # Throws error.
 print x.b.c

任何人都可以解释上面代码中的错误,因为NoneType object has no attribute c. 清楚地表明print self.__dict__a都已插入对象的字典中。

我的用例是有一个对象,可以在需要时动态为其添加属性。就像我应该可以使用的一样:

b

还有,还有其他方法可以实现我的目标吗?

更新:发现错误,x = A() x.a = 1 x.b.c = 2 x.d.e.f.g = 3 应该返回一个值。

更正代码

__getattr__

1 个答案:

答案 0 :(得分:2)

__getattr__是在请求获取属性但在请求的对象中不可用时调用的。

假设x没有a,则呼叫类似

result = x.a

在功能上等同于

result = getattr(x, "a")

在功能上等同于

result = type(x).__getattr__(x, "a")

通常与

相同

result = x.__getattr__("a")

仅当__getattr__绑定到对象而不是类(which may not work)时,后两个变量才有所不同

如您在此处看到的,__getattr__应该返回a本应具有的值。

它也可以直接设置属性,以便进一步的获取请求不会再次调用__getattr__,而是直接由Python处理。这是否有意义取决于特定的用例(在您的用例中确实如此)。

x.b.c = 2在这里通常翻译为类似

setattr(x.__getattr__("b"), "c", 2)

同样,__getattr__必须在此处返回设置了属性c的对象。