Question: Instances


#1

Hi Guys! Can someone tell more about the question below:

Why Python does not allow to pass an argument to a class when we create an instance:
For instance,

class Car(object):
condition = "new"
def init(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg

my_car = Car("DeLorean", "silver", 88)

Why not? my_car = Car(model, color, mpg)


#2

We would need to define the three variables, before the call:

model = "DeLorean" 
color = "silver"
mpg = 88

my_car = Car(model, color, mpg)

#3

Can we define them globally or just as member?


#4

In the above example they are global, but they would have been better written in function scope to protect the global namespace. For instance, I tested this and it works...

class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg

my_car = Car("DeLorean", "silver", 88)

def add_car():
    model = raw_input("Model:")
    color = raw_input("Color:")
    mpg = raw_input("MPG:")
    return Car(model, color, mpg)

new_car = add_car()

#5

You are awesome for the second part of your answer! Thank you so much!

def add_car():
model = raw_input("Model:")
color = raw_input("Color:")
mpg = raw_input("MPG:")
return Car(model, color, mpg)

new_car = add_car()