200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python中类的参数怎么传_如何将整个类作为参数传递给另一个类的方法

python中类的参数怎么传_如何将整个类作为参数传递给另一个类的方法

时间:2024-01-05 15:06:13

相关推荐

python中类的参数怎么传_如何将整个类作为参数传递给另一个类的方法

首先,不需要在Python中指定类型。因此,如果您希望method获取一个First实例,只需执行以下操作:class Second():

def __init__(self, c, d):

pass

def method(self, first):

pass

my_first = First(0, 1)

my_second = Second(2, 3)

my_second.method(my_first)

我相信这回答了你真正的问题,那就是:If I have several instances of the class first and need to pass any of them not specifying which one to method of class Second…

如果您想确保参数实际上是First,那么您可以始终添加assert isinstance(first, First)或{}或其他任何东西,但通常您不希望在Python中这样做。“duck-typing”的全部要点是您编写一个接受“任何类似于First实例”的函数,而不是采用“一个First实例”的函数。在

然后你说:Now I need to mutate variables from the First class inside the method of a second class:

所以…就这么做吧。您的示例在First类中没有任何属性,因此让我们添加一些:

^{pr2}$

现在,让我们在Second.method中使用它们:class Second():

def __init__(self, c, d):

self.total = c + d

def method(self, first):

first.total += self.total

所以:>>> my_first = First(0, 1)

>>> my_first.total

1

>>> my_second = Second(2, 3)

>>> my_second.total

5

>>> my_first.total += 2

>>> my_first.total

3

>>> my_second.method(my_first)

>>> my_first.total

8

或者,如果你想改变类First中的class属性……你甚至不需要一个First实例:First.my_class_attribute = 1

如果您真的需要传递一个类本身…那么,类和其他任何东西一样都是一个常规值:class Second():

def __init__(self, c, d):

pass

def method(self, cls):

pass

my_second = Second(1, 2)

my_second.method(First)

您可以从method内访问cls的类属性,就像在传递实例时访问实例属性一样容易。在

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。