hellolouis 发表于 2020-6-9 11:41:41

如何把元组元素作为类属性实例化一个对象?

本帖最后由 hellolouis 于 2020-6-9 11:44 编辑

class Car():
    def __init__(self, make, model, transmission, color, doors=4, features={}):
      self.make = make
      self.model = model
      self.transmission = transmission
      self.color = color
      self.doors = doors
      self.features = features


def putin():
    make = input('make: ')
    model = input('model: ')
    transmission = input('transmission: ')
    color = input('color: ')
    doors = 4
    features={}
    features_key = input('features_key: ')
    features_value = input('features_value: ')
    features = features_value
    return make, model, transmission, color, doors, features


先用 putin() 生成一个元组,a = ('a', 'b', 'c', 'd', 4, {'11': '22'})

一个比较麻烦的方法实例化: car = Car(a,a,a,a,a,a)

请问有没有更简单的方法来实例化对象?

hrp 发表于 2020-6-9 11:48:35

car = Car(*a)

Twilight6 发表于 2020-6-9 11:50:22

a = ('a', 'b', 'c', 'd', 4, {'11': '22'})
car = Car(*a)
通过解包

Twilight6 发表于 2020-6-9 11:51:35

hrp 发表于 2020-6-9 11:48


{:10_250:} 被你抢先了 {:10_245:}

hellolouis 发表于 2020-6-9 11:57:15

Twilight6 发表于 2020-6-9 11:51
被你抢先了

{:5_109:}最快不是最好的,你不说我都不知道这个带星号的叫解包

Twilight6 发表于 2020-6-9 12:00:03

hellolouis 发表于 2020-6-9 11:57
最快不是最好的,你不说我都不知道这个带星号的叫解包

{:7_113:}
页: [1]
查看完整版本: 如何把元组元素作为类属性实例化一个对象?