繁体   English   中英

当我在 class 方法中初始化像 m1 这样的变量时不使用“self”键时到底发生了什么。 m1 是本地变量,object 还是 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 ),则名称( m1m2 ..)在 scope 中的 go 时丢失(当__init__(...)返回时)

这实际上与在 function 中使用名称相同 - 它们仅存在于该 scope 中,除非放在其他地方!

如果您不使用self ,您只是将值分配给一个局部变量,一旦 function 完成就无法访问该变量。

如果您使用self.m1 ,该值将分配给 self 的一个属性,以后可以访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM