Tms*_*s91 1 python oop class init
我可能缺乏非常基本的Python基础。我正在处理别人制作的脚本。
我有一个脚本,比方说My_Class
,其中的代码是:
import thing1
import thing_2
...etc
class My_Class:
def __init__(self, arg1, arg2 ...etc):
self.argument_1 = arg1
self.argument_2 = arg2
...etc
Run Code Online (Sandbox Code Playgroud)
__init__
my_class 的参数未作为参数传递给 my_class是否正确?(my_class 根本没有参数)
如果类没有参数,如何arg1, arg2 ...etc
传递参数?my_class
难道不应该吗
import thing1
import thing_2
...etc
class My_Class(arg1, arg2 ...etc):
def __init__(self, arg1, arg2 ...etc):
self.argument_1 = arg1
self.argument_2 = arg2
...etc
Run Code Online (Sandbox Code Playgroud)
反而?
笔记:
该类不会被实例化,仅直接在该类上调用其方法,即:
My_Class(arg1, arg2 ...etc).method_1()
Run Code Online (Sandbox Code Playgroud)
我希望这些信息能让您更好地理解为什么我们可以调用我们的类,这些参数在哪里,类的参数在哪里等等。
那么,我们来谈谈__call__
:
考虑__call__
在课堂上实施。换句话说,它使类的实例可以被调用,“this”是您可以放在()
实例后面的原因,对吗?当您以这种方式调用实例时,__call__
实际的方法就是被调用!如果您在__call__
方法中将参数定义为参数,则可以在调用实例时传递参数。
class A:
def __call__(self, arg):
print('It is calling', arg)
instance = A()
instance('foo')
Run Code Online (Sandbox Code Playgroud)
现在我们知道类本身是 type 的实例 --> type
:
class A:
pass
print(isinstance(A, type)) # True
Run Code Online (Sandbox Code Playgroud)
因此,“他们的”类中必须有一种__call__
方法(最好是元类),当然type
. ()
这就是我们可以放在类后面来调用它并向其传递参数的原因。
当您将括号放在类前面时,您实际上是在使用此处给定的参数调用__call__
类的此方法,...type
arg1
arg2
等等,但是在哪里__init__
?哪里__new__
?他们如何被召唤?
事实上,它们是在类的方法内部使用您传递的参数进行调用的。首先,如果它返回类的实例,则像普通实例方法一样被调用。__call__
type
__new__
__init__
现在我将演示我之前解释过的内容:(所有类的默认元类是type
class,但我将使用我的元类向您展示详细信息)
class Mymeta(type):
def __call__(cls, *args, **kwargs):
print(f"Metaclass's __call__ gets called with: {args} and {kwargs}")
new_created_instance = cls.__new__(cls, *args, **kwargs)
if isinstance(new_created_instance, cls):
new_created_instance.__init__(*args, **kwargs)
return new_created_instance
class A(metaclass=Mymeta):
def __new__(cls, *args, **kwargs):
# return 10 # <-- If you uncomment this, __init__ won't get called.
return super(A, cls).__new__(cls)
def __init__(self, name, **kwargs):
print(
'This is printed only because'
' we called it inside `__call__` method of the meta class'
)
self.name = name
obj = A('soroush', age=5)
Run Code Online (Sandbox Code Playgroud)
输出 :
Metaclass's __call__ gets called with: ('soroush',) and {'age': 5}
This is printed only because we called it inside `__call__` method of the meta class
Run Code Online (Sandbox Code Playgroud)
请注意两件事,首先,我们在类前面传递的所有参数都直接传递给__call__
元类的方法。其次,正如您所看到__call__
的是和Mymeta
的调用者。__new__
__init__