简体   繁体   English

Python可变属性数

[英]Python variable number of attributes

I'm new to ptyhon I'm trying to do something that should be quite simple but I can't do it. 我是ptyhon的新手,我正在尝试做一些应该很简单的事情,但我做不到。

I have to create objects that will have a different number of attributes each time. 我必须创建每次具有不同数量属性的对象。 For example : 例如 :

OBJECT A
    Attribute 1
    Attribute 2
    Attribute 3
OBJECT B
    Attribute 1
    Attribute 2

The attribute 1 will always be there (with different values but there will be at least one attribute in the object). 属性1将始终存在(具有不同的值,但对象中将至少有一个属性)。 I've created an example class : 我创建了一个示例类:

class car():
    def__init__(self, Color, **kwargs):
        self.Color = Color 

        for key, value in kwargs.iteritems():
            setattr(self, key, value)

So now I have to call the contructor, but as the number of attributes will be variable, how should I do it ? 因此,现在我必须调用构造函数,但是由于属性的数量是可变的,我该怎么办?

CAR1_ATTRIBUTES = (Passengers = 5, Tires = 4)
CAR2_ATTRIBUTES = (DriverName = "John", Tires = 4, DoorsNumber = 5)
CAR3_ATTRIBUTES = (DriverName = "Tom", Velocimeter = "Y", DoorsNumber = 4)

CarsList = []
for i in range(0,3):
    CarObject = Car("RED", RESTOFATTRIBUTES)
    CarsList.append(CarObject)

"RESTOFATTRBUTES" will be variable (it could be one single argument or 1563...) “ RESTOFATTRBUTES”将是变量(可以是一个参数或1563 ...)

You can pass any number of named parameters key = value , for example, 您可以传递任意数量的命名参数key = value ,例如,

Car("RED", Passengers = 5, Tires = 4)

and they will be seen as the key : value pairs of the dictionary kwargs. 并且它们将被视为字典kwargs的key : value对。 Or directly pass the dictionary: 或直接通过字典:

RESTOFATTRIBUTES = {"Passengers": 5, "Tires": 4}
Car("RED", **RESTOFATTRIBUTES)

You don't have to use the ** syntax. 您不必使用**语法。 You could also have used the * syntax. 您也可以使用*语法。 You define the function def Car(color, *args): . 您定义函数def Car(color, *args): In the body of the funcion, args is then a tuple where the first element corresponds to, say, Passengers, the second corresponds to, say, Tire, etc. You call Car this way: 在函数的主体中,args然后是一个元组,其中第一个元素对应于乘客,第二个元素对应于Tire等。您可以这样称呼Car

Car("RED", 5, 4)

or 要么

RESTOFATTRIBUTES = (5, 4)
Car("RED", *RESTOFATTRIBUTES)

There can be more than only two extra attributes, if the body of the function CAR manages it. 如果功能CAR的主体对其进行管理,则只能有两个以上的额外属性。

This was a duplicate in a way, but there was nothing wrong in providing an answer in the specific context of this question. 在某种程度上,这是重复的,但是针对该问题的特定上下文提供答案没有错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM