我对Python比较陌生,尽管我用谷歌搜索了一下,但我看不出它是如何工作的。为什么最后两行打印错误的数据类型。我了解string和int之间的区别,但希望了解其他数字,如浮点数、双精度数等,以及如何确保正确的数据类型。
在c#中,构造函数负责处理类。我们如何在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;
}发布于 2021-10-23 06:01:18
如果我没记错的话,在ProductID中输入的值必须是" 888“,而不仅仅是888。在Total_Value中,浮点数是一个像1.88这样的十进制数(就像你的代码中的一样)。
例如,1是整型,"1“是字符串,1.00是浮点型,如果你想改变数据类型,你可以使用像str(),int()这样的函数。
希望这会对你有所帮助,我也是stackoverflow的新手,所以如果有什么问题,我真的很抱歉。
https://stackoverflow.com/questions/69685462
复制相似问题