首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python类构造函数

Python类构造函数
EN

Stack Overflow用户
提问于 2021-10-23 05:43:17
回答 1查看 64关注 0票数 1

我对Python比较陌生,尽管我用谷歌搜索了一下,但我看不出它是如何工作的。为什么最后两行打印错误的数据类型。我了解string和int之间的区别,但希望了解其他数字,如浮点数、双精度数等,以及如何确保正确的数据类型。

在c#中,构造函数负责处理类。我们如何在python中实现同样的功能呢?

代码语言:javascript
运行
复制
   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;
 
}
EN

回答 1

Stack Overflow用户

发布于 2021-10-23 06:01:18

如果我没记错的话,在ProductID中输入的值必须是" 888“,而不仅仅是888。在Total_Value中,浮点数是一个像1.88这样的十进制数(就像你的代码中的一样)。

例如,1是整型,"1“是字符串,1.00是浮点型,如果你想改变数据类型,你可以使用像str(),int()这样的函数。

希望这会对你有所帮助,我也是stackoverflow的新手,所以如果有什么问题,我真的很抱歉。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69685462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档