osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Class Issue`


On 05/03/2019 22:39, Milt 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()

The behaviour you should expect even from C++ (a language I have no 
respect for) is a compile-time error complaining that you are passing an 
integer to a string parameter and vice versa.  Python is a dynamically 
typed language; it doesn't enforce any restrictions on what types of 
object can be bound to any given name.  This is occasionally a surprise 
when you're being careless, but it really shouldn't break your expectations.

-- 
Rhodri James *-* Kynesim Ltd