簡體   English   中英

有沒有一種簡單的方法可以在Python類中分配實例變量?

[英]Is there a simple way of assigning instance variables in a Python class?

在Python 2.7中定義類時,將變量輸入init()函數,然后使用例如self.x將其分配給實例變量self.x

class NewClass(object): 
  def __init__(self, x, y):      
    self.x = x                    
    self.y = y

如果使用大量變量,是否可以簡化此過程,即不必顯式定義每個實例變量?

還是有充分的理由明確定義它們?

如果您想要不可變的東西,則collections.namedtuple很有用:

>>> from collections import namedtuple
>>> NewClass = namedtuple('NewClass', 'x y')
>>> obj = NewClass(x=10, y=14)

>>> obj
NewClass(x=10, y=14)
class NewClass(object): 
  def __init__(self, **kwargs):
    self.validate(kwargs) # optional      
    self.__dict__.update(kwargs)

但整個想法有點臭

您還可以使用帶有允許的kwargs鍵的靜態集,並validate是否會檢查傳遞的kwargs包含該集合的子集

您可以使用__dict__

class NewClass:
    def __init__(self, *args):
        self.headers = ["var{}".format(i+1) for i in range(len(args))]#optional, can use an list of variable names you are expecting
        for a, b in zip(self.headers, args):
            self.__dict__[a] = b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM