Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在某些操作之前或之后将变量声明为实例变量_Python 3.x - Fatal编程技术网

Python 3.x 在某些操作之前或之后将变量声明为实例变量

Python 3.x 在某些操作之前或之后将变量声明为实例变量,python-3.x,Python 3.x,我在相当多的地方对向类定义中添加变量感到困惑。比如: class net: def __init__(self, a,b,c): self.a=b*3 self.b=b # what if do like this? def __init__(self, a, b) self.b=b self.a=a*self.b 参见def\uuuu init\uuuuu()不过是一个为该类变量赋值的构造函数。你所做的就像是将b的值赋值给

我在相当多的地方对向类定义中添加变量感到困惑。比如:

class net:
  def __init__(self, a,b,c):
     self.a=b*3
     self.b=b
     # what if do like this?
  def __init__(self, a, b)
     
     self.b=b
     self.a=a*self.b
参见
def\uuuu init\uuuuu()
不过是一个为该类变量赋值的构造函数。你所做的就像是将b的值赋值给类变量b,并且你将一个times类变量b赋值给a。对于该实例,你也可以执行
self.a=a*b
它会给出相同的答案。 检查示例-

    class Test2:
  def __init__(self,a,b):
    self.a=a
    self.b=b*self.a
    self.c=b*a
  def printf(self):
    print("Value of a is {} ,value of b is {} and value of c is {}".format(self.a,self.b,self.c))##c output would be same as b

f=Test2(3,3)
f.printf()
输出

Value of a is 3 ,value of b is 9 and value of c is 9
我希望我已经让你明白了