__init __()内部和外部变量之间的差异 [英] difference between variables inside and outside of __init__()

查看:88
本文介绍了__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天全站免登陆