[英]what happens when you don't pass 'self' while declaring a method inside a inherited class
[英]What exactly happens when i don't use "self" key while initialising a variable like m1 inside a class method. m1 is local,object or class variable?
class Student:
def __init__(self,m1,m2):
m1=m1
m2=m2
print(m1+m2)
s1=Student(10,20)
s2=Student(20,30)
print(Student.m1)
#i 刚刚开始 oops 概念,所以现在有点困惑。 编写“print(Student.m1) 或 print(s1.m1)”时出现编译时错误“AttributeError: type object 'Student' has no attribute 'm1'”。
如果您不将值设置为属性(通过self
),则名称( m1
, m2
..)在 scope 中的 go 时丢失(当__init__(...)
返回时)
这实际上与在 function 中使用名称相同 - 它们仅存在于该 scope 中,除非放在其他地方!
如果您不使用self
,您只是将值分配给一个局部变量,一旦 function 完成就无法访问该变量。
如果您使用self.m1
,该值将分配给 self 的一个属性,以后可以访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.