Class Issue`

Kevin Hu hxy9243 at gmail.com
Tue Mar 5 18:11:48 EST 2019


I believe for the correct behavior you’ll need:

myCar = Car(color=‘blue’, miles=15000)

myCar = Car(miles=25000, color=‘orange’)

In which case both objects will be initialized as the way you’d expect. 

Python is a language with very weak typing, and it’ll happily shoehorn data into variables even when you don’t expect it to. In this case it’ll assign arguments to parameters in order, which is the expected behavior.

Regards,
Kevin

> On Mar 5, 2019, at 16:39, Milt <t2 at NetRH.com> wrote:
> 
> The following code gives me unusual results - base on experience with C++.
> 
> class Car:
>    # carColor = None
>    # mileage = None
> 
>    def __init__(self, color = None, miles = None):
>       self.mileage = miles
>       self.carColor = color
> 
>    def print(self):
>       print(f"Color:   {self.carColor}")
>       print(f"Mileage: {self.mileage}")
> 
> myCar = Car('blue', 15000)
> myCar.print()
> 
> print()
> 
> myCar = Car(25000, 'orange')
> myCar.print()
> 
> 
> When executed the following results:
> 
> Color:   blue
> Mileage: 15000
> 
> Color:   25000
> Mileage: orange
> 
> It appears that the constructor ignores the assignment statements and makes the assignment based on the ordering in the __init__ declaration.
> -- 
> Regards,
> 
> Milt
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list