2013-02-07 24 views
0

在Python中(我在这里说2,但也有兴趣知道约3)是否有一种方法可以预先定义所有需要的实例变量(成员字段)的列表,例如,使其成为一个错误使用一个你还没有定义的地方?在Python中,你能提前声明所有可用的实例变量吗?

喜欢的东西

class MyClass(object): 
    var somefield 
    def __init__ (self): 
     self.somefield = 4 
     self.banana = 25  # error! 

有点像您在Java,C++,PHP,做等

编辑:

我想这种事情的原因是早期发现使用最初尚未设置的变量。看来,一个棉绒实际上会挑这些错误,没有任何额外的管道,所以也许我的问题是没有意义的...

+0

你为什么要这个? – Dhara

+0

你为什么想要做这样的事情? –

+0

@mattwritescode,Dhara:在某些情况下使用'__slots__'可以使代码更快。除此之外,它可以强制执行某些OOP操作。看到[这里](http://stackoverflow.com/questions/472000/python-slots) –

回答

4

为什么是的,你可以。

class MyClass(object): 
    __slots__ = ['somefield'] 
    def __init__ (self): 
     self.somefield = 4 
     self.banana = 25  # error! 

mind the caveats

+0

同时回答! :) - 但你的代码:(。我想我会删除我的...然后... – mgilson

+0

使用__slots__冻结类不是一个好主意 – Dhara

+0

并且介意'__slots__'主要是一个节省内存的工具 –

0

您可以使用上面贴了答案,但对于更多的“Python化”的做法,尝试(链接到code.activestate.com)

以供将来参考列出的方法,直到我可以计算出如何链接到网站,这里是代码:

def frozen(set): 
    """Raise an error when trying to set an undeclared name, or when calling 
     from a method other than Frozen.__init__ or the __init__ method of 
     a class derived from Frozen""" 
    def set_attr(self,name,value): 
     import sys 
     if hasattr(self,name):         #If attribute already exists, simply set it 
      set(self,name,value) 
      return 
     elif sys._getframe(1).f_code.co_name is '__init__':  #Allow __setattr__ calls in __init__ calls of proper object types 
      for k,v in sys._getframe(1).f_locals.items(): 
       if k=="self" and isinstance(v, self.__class__): 
        set(self,name,value) 
        return 
     raise AttributeError("You cannot add attributes to %s" % self) 
    return set_attr 
+0

这很聪明。但正如Martijn Pieters指出的那样,似乎pylint实际上挑选了我试图阻止的那种错误,而没有任何额外的管道。所以也许我的问题是多余的... – Seb