osdir.com

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

Class Issue`


Milt,

On 6/03/19 11:39 AM, 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()
> 
> 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.


It is risky to decide that Python should behave in a certain fashion, 
just because another language does. Would you decide that the word 
"blue" may not be used because in French it is "bleu"? If all 
programming languages did look/work the same way, why would there be 
multiple languages? However, your understanding of C++ gives you a 
flying start with Python - apart from a few pesky 'gotchas'!


In the term "ignores the assignment statements", what "assignment 
statements" are being discussed?


Yes, without keywords, the positional rule applies.

myCar = Car('blue', 15000)
is the same as:
myCar = Car(color = 'blue', miles = 15000)

Instead of:
myCar = Car(25000, 'orange')
try:
myCar = Car(miles=25000, color='orange')

If you've gone to the trouble of defining keyword-arguments in the 
method, greater satisfaction will be gained from calling the method 
similarly (and cause less confusion on the part of your readers!)


Meantime I have a very low-mileage Edsel in an attractive lemon color, 
going cheap...


Jokes aside: using the __str__() and __repr__() "magic methods" is more 
'pythonic' than adding a print method to a class.

For a nicely-formatted output (albeit without mentioning that it is 
describing a "Car" or "myCar" - per print(), above):

      def __str__(self):
         return f"Color:   {self.carColor}\nMileage: {self.mileage}"
...
myCar = Car(color = 'blue', miles = 15000)
print( myCar )

For extra credit, seeing we're talking about 'being pythonic': car_color 
and my_car.


Alternately, to present the output formatted as a class definition/ready 
for instantiation:

      def __repr__(self):
         return f"Car( color={self.car_color}, miles={self.mileage} )"

NB if both methods appear in a class, printing the class (ie print( 
my_car ) ) will prefer __repr__() over __str__().


All the best...
-- 
Regards =dn