__init__() 内外变量的区别 [英] difference between variables inside and outside of __init__()

查看:23
本文介绍了__init__() 内外变量的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了名称之外,这些类之间还有什么区别吗?

Is there any difference at all between these classes besides the name?

class WithClass ():
    def __init__(self):
        self.value = "Bob"
    def my_func(self):
        print(self.value)

class WithoutClass ():
    value = "Bob"

    def my_func(self):
        print(self.value)

如果我使用或不使用 __init__ 方法来声明变量 value 有什么区别吗?

Does it make any difference if I use or don't use the __init__ method for declaring the variable value?

我主要担心的是我会以一种方式使用它,这会给我带来更多的问题.

My main worry is that I'll be using it one way, when that'll cause me further problems down the road.

推荐答案

__init__ 之外的变量集属于类.它们由所有实例共享.

Variable set outside __init__ belong to the class. They're shared by all instances.

__init__(以及所有其他方法函数)内部创建并以self. 开头的变量属于对象实例.

Variables created inside __init__ (and all other method functions) and prefaced with self. belong to the object instance.

这篇关于__init__() 内外变量的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆