【问题标题】:What is the type of the object that instantiates classes in python?在 python 中实例化类的对象的类型是什么?
【发布时间】:2020-06-30 16:29:49
【问题描述】:

我有一个我什至不知道如何搜索的问题。以这个简单的类为例:

class Student(object):
    def _init_(self):
        self.id = 0
    
    def inc(self):
        self.id += 1
 
std_gen = Student

std_gen 的类型是什么? 我试过了:

print(type(std_gen))

我得到了这个:

<class 'type'>

我需要找到它的类型并将其添加到文档字符串中。我什至找不到返回Trueisinstance(std_gen, something)something

编辑:我发现 isinstance(std_gen, type) 返回 True 但这在文档字符串中几乎没有意义。这是什么意思?

【问题讨论】:

  • std_gen 只是Student 的另一个名称,您实际上并没有实例化该类(应该写成Student())。
  • 不可能相同,因为std_gen 充当构造函数,std_gen() 返回的是该类的实例。
  • @PavanChandaka 你能解释一下吗?我浏览了该页面,但找不到答案。

标签: python class types docstring


【解决方案1】:

Class Student 是“type”类型的实例。有关更多信息,请参阅元类。所以 type(Student) 是“类型”。所以

s = Student()
std_gen = Student
type(s) // <class 'Student'>
type(std_gen) // <class 'type'>

综上所述,s 是 Student 的实例,Student 是类型的实例,stu_gen 只是 Student 的别名。

【讨论】:

    【解决方案2】:

    我相信这就是您正在寻找的解决方案。

    print(type(std_gen()))
    

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 2018-10-29
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 2021-09-28
      • 2013-02-15
      • 2011-02-05
      相关资源
      最近更新 更多