I'm relatively new to Python and despite googling, I can't see how this works. Why are the last two lines printing the wrong data type. I understand the difference between string and int, but want to understand other numerics like float, doubles etc and how I can ensure the right data type..
In c#, the constructors would take care of the class. How do we achieve the same in python?
class Results:
Product: [str]
Total_Value: [int]
Quantity: [int]
ProductID: [str]
def __init__ (self, Product: str, Total_Value: int, Quantity: int, ProductID: str):
self.Product=Product
self.Total_Value=Total_Value
self.Quantity=Quantity
self.ProductID=ProductID
r=Results("hello",1.88,3.888,888)
print(r.ProductID)
print(type(r.ProductID)) # why is thie not a string? ? This prints 'int' but ProductID should be string
print(type(r.Total_Value)) # why is this not an int? This should be 'int' but Total_Value is 'float'
In c#, the output is correct and I was expecting something similar in Python
void Main()
{
var b =new Bunny();
b.Name="Tom";
b.number=3;
b.number2=3;
Console.WriteLine(b.number.GetType()); //this prints Int64 as it should
Console.WriteLine(b.number2.GetType()); //this prints Double as it should
}
public class Bunny
{
public string Name;
public System.Int64 number;
public double number2;
}
[int]is not a valid PEP 484 type. Second, type annotations in Python are never enforced by the Python interpreter, only by external tools like mypy. Third, you passed an integer forProductID. Even if Python did enforce type signatures on its own (which it doesn't), that would be an error. If you pass an integer where a string is expected in C#, that's an error, not some sort of exciting but questionably-desgined implicit coercion# why is thie not a string?because you very clearly passed anintobject as the 4th argument to the constructor:r=Results("hello",1.88,3.888,888), which is the parameter that gets assigned toself.ProductID. Why did you expect anything different?