Python类实例化中的不同行为

2024-04-19 15:04:58 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我一直在尝试类和对象&;陷入了一个疑问。我试着用谷歌搜索,但我不知道该怎么搜索这个。下面是代码片段

class Demo:
    def __init__(self):
        print("In init")

    def __call__(self,item):
        print("Got {} in call".format(item))

    def print(self):
        print("Evaluating print()")

完成上述程序后,我尝试了以下几个命令:

>>>a=Demo
>>>a.print()
Traceback (most recent call last):
  Python Shell, prompt 3, line 1
builtins.TypeError: print() missing 1 required positional argument: 'self'
>>>a.print(a)
Evaluating print()
>>>b=Demo()
In init
>>>b.print()
Evaluating print()
>>>type(a)
<class 'type'>
>>>type(b)
<class '__main__.Demo'>

我的问题是:
1) 创建对象时a=Demob=Demo()之间有什么区别?
2) 为什么a.print()在第一种情况下不起作用,而a.print(a)却起作用了?
3) 在这种情况下,b('item')将工作,以Got item on call的形式给出输出,而在a('item')的情况下则不工作。为什么是这样

注意:我使用的是python3.6


Tags: 对象inselfinitdemodeftype情况
1条回答
网友
1楼 · 发布于 2024-04-19 15:04:58

a=Demo不创建任何对象,它只是将Demo类对象赋给变量a

你真的展示了这一点:

>>>type(a)
<class 'type'>
>>>type(b)
<class '__main__.Demo'>

在Python中,类也是类型为type的对象

Demo替换a来比较使用a时发生的情况

注意,类是第一类对象,您可以像对待任何其他对象一样对待它们,比如listinttype实际上只是一个构造函数,比如listint

>>> list()
[]
>>> int()
0
>>>
>>> MyClass = type('MyClass', (), {})
>>> MyClass
<class '__main__.MyClass'>
>>> MyClass()
<__main__.MyClass object at 0x10406fe80>
>>>

类型构造函数接受三个参数类的名称作为一个字符串(注意,您没有将它赋给同一个变量名),一个基元组,这里是空的,所以它隐式地是object,就像您做了class A: pass,还有名称空间,所以是从属性名到属性的映射。方法只是属于类的命名空间的函数对象

Init signature: type(self, /, *args, **kwargs)
Docstring:
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
Type:           type

下面是用type构造函数创建的类的一个稍微不那么普通的示例,它也有方法:

>>> Foo = type('Foo', (), {'__init__': lambda self, x: setattr(self, 'x', x), 'bar': lambda self: self.x})
>>> f = Foo(42)
>>> f.bar()
42

docs中阅读更多

相关问题 更多 >