python - 如何在 __init__ 中定义属性

标签 python properties constructor

我希望通过成员函数在类中定义属性。 下面是一些测试代码,显示我希望它如何工作。但是我没有得到预期的行为。

class Basket(object):

  def __init__(self):
    # add all the properties
    for p in self.PropNames():
      setattr(self, p, property(lambda : p) )

  def PropNames(self):
    # The names of all the properties
    return ['Apple', 'Pear']

  # normal property
  Air = property(lambda s : "Air")

if __name__ == "__main__":
  b = Basket()
  print b.Air # outputs: "Air"
  print b.Apple # outputs: <property object at 0x...> 
  print b.Pear # outputs: <property object at 0x...> 

我怎样才能让它发挥作用?

最佳答案

您需要在类上设置属性(即:self.__class__),而不是在对象上(即:self)。例如:

class Basket(object):

  def __init__(self):
    # add all the properties
    setattr(self.__class__, 'Apple', property(lambda s : 'Apple') )
    setattr(self.__class__, 'Pear', property(lambda s : 'Pear') )

  # normal property
  Air = property(lambda s : "Air")

if __name__ == "__main__":
  b = Basket()
  print b.Air # outputs: "Air"
  print b.Apple # outputs: "Apple"
  print b.Pear # outputs: "Pear"

就其值(value)而言,您在循环中创建 lamda 时对 p 的使用并没有提供您期望的行为。由于 p 的值在循环过程中发生了变化,因此循环中设置的两个属性都返回相同的值:p 的最后一个值。

关于python - 如何在 __init__ 中定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1454984/

相关文章:

powershell 获取 aduser 扩展属性12

ios - 如何从 AppDelegate.m 访问一些实例类变量

c++ - 委派构造函数 : an initializer for a delegating constructor must appear alone

C++ 一个参数 bool 构造函数和 "new"关键字 : Logic Error

python - 尝试创建 3x3x3 立方体,但在 OpenGL 中创建了 4x4x4

javascript - 如何使用Python登录网页?

python - 如果 pandas series 的值是一个列表,如何获取每个元素的子列表?

java - 如何获取属性名称而不是属性值?

java - java.lang.Object x = new Foo() 的 C++ 等价物是什么?

python - 你能在 Django 中执行多线程任务吗?