![](/img/trans.png)
[英]Python assignment to self in constructor does not make object the same
[英]In python does self require any object of its same type?
我正在阅读9.3.2。 来自python文档的类对象和我希望有人可以清理以下内容:
两个场景如何回归“你好世界”? 我有点理解的第一个例子(至少我相信我这样做),因为self引用了对象本身的'MyClass',我想在第二个实例中将'm'传递给self也是这样做的? 函数'self'是否只需要对'MyClass'对象的任何引用?
>>> class MyClass:
... """A simple example class"""
... i = 12345
... def f(self):
... return 'hello world'
...
>>> MyClass.f(MyClass)
'hello world'
>>> m = MyClass()
>>> MyClass.f(m)
'hello world'
Python是“duck-typed”,这意味着只要它提供了正确的接口, self
就是什么类型并不重要。 在这里, self
不在函数体中使用,所以你可以将任何东西传递给MyClass.f
并且它可以工作。
>>> MyClass.f(None)
'hello world'
>>> MyClass.f(9)
'hello world'
>>> MyClass.f("foo")
'hello world'
MyClass.f('what the...')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-cca57c03fecc> in <module>()
----> 1 MyClass.f('what the...')
TypeError: unbound method f() must be called with MyClass instance as first argument (got str instance instead)
mc = MyClass()
mc.f('what?')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-bcd3830312d3> in <module>()
----> 1 mc.f('what?')
TypeError: f() takes exactly 1 argument (2 given)
在第一个实例中,该函数需要MyClass
的实例作为第一个参数。 在第二个中,实例被隐式传递。 字符串参数What?
因此,这是函数的第二个参数是出乎意料的。
你可能想要的:
class MyClass:
@staticmethod
def f():
print('hello world')
>>> MyClass.f()
hello world
mc = MyClass()
>>> mc.f()
hello world
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.