如何在__init__中定义属性 [英] How to define properties in __init__

查看:448
本文介绍了如何在__init__中定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour.

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 __ code> self )。例如:

You need to set the properties on the class (ie: self.__class__), not on the object (ie: self). For example:

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"

在创建lamdas时,使用 p 在循环中,不会给出你期望的行为。由于 p 的值在执行循环时发生更改,因此循环中设置的两个属性都返回相同的值: p

For what it's worth, your usage of p when creating lamdas in the loop, doesn't give the behavior that you would expect. Since the value of p is changed while going through the loop, the two properties set in the loop both return the same value: the last value of p.

这篇关于如何在__init__中定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆