Class Python多类函数
首先,很抱歉,如果这个名字是可怕的误导。事实上,我不确定我到底想做什么。出于同样的原因,我在这个主题上的搜索可能已经缺失,所以如果这是我真的应该能够查找到的东西,我道歉 我要做的是创建一个函数,使用两个独立类中对象的变量,然后为后一个类中的对象更改变量Class Python多类函数,class,python-3.x,Class,Python 3.x,首先,很抱歉,如果这个名字是可怕的误导。事实上,我不确定我到底想做什么。出于同样的原因,我在这个主题上的搜索可能已经缺失,所以如果这是我真的应该能够查找到的东西,我道歉 我要做的是创建一个函数,使用两个独立类中对象的变量,然后为后一个类中的对象更改变量 class Type_1: def __init__(self, a, b, c, d, e): self.variable1 = a self.variable2 = b self.var
class Type_1:
def __init__(self, a, b, c, d, e):
self.variable1 = a
self.variable2 = b
self.variable3 = c
self.variable4 = d
self.variable5 = e
def push(target):
self.variable1 += 5
target.variable2 -= int(self.variable5 - target.variable3)
class Type_2:
def __init__(self, a, b, c, d, e):
self.variable1 = a
self.variable2 = b
self.variable3 = c
self.variable4 = d
self.variable5 = e
该计划旨在找到一种方法,使类型_1中的push函数能够识别任何类中的对象,前提是该对象具有必要的变量作为其目标,从而影响所述对象,但我的方法不起作用
编辑:
问题是,当我使用push函数时,python总是专门查找属于名为target的类的变量。它不会根据我输入的内容查找类,即
push(John)
当我试图编辑John.variable2时,仍然希望尝试编辑target.variable2
Edit2:多亏了mata和Mikhail Karavashkin,这个问题现在已经解决了。如果考虑到我对你问题的更正(
def
,对于\uu init\uuu
和self
对于push(self,target
),你似乎是在向课堂而不是向实例推进,这将起作用:
>>> a = Type_1(1,2,3,4,5) # making an instance of Type_1
>>> b = Type_2(1,2,3,4,5) # making an instance of Type_2
>>> a.push(b) # pushing one to another
>>> b.variable2 # it worked!
0
>>> a.variable1 # it worked!
6
“根本不起作用”有点不清楚。到底是什么不起作用,以及您是如何尝试使用它的。也就是说,您的
\uuuu init\uuuu
s缺少def
,push(target)
应该是push(self,target)
init的问题只是我复制得不好。在我试图运行的版本中,它有def。感谢您指出这一点,我将立即更改它。至于它根本不起作用,我的意思是python会查找特定的变量target.variable2,即使我将函数用作push(“John”)我不确定在什么样的环境下需要将多个对象关联在一起(我也不怀疑有时您可能需要这种行为),但我建议使用getter、setter和properties来充实您可能需要的内容。edit:找到了一个解决此问题的答案。这对我不适用。但是,它给出了以下信息:TypeError:push()接受1个位置参数,但2个被赋予将push
的签名更改为push(目标)
到push(自我,目标)