【问题标题】:What is the difference between using self.classvariable and class.classvariable inside methods?在方法内部使用 self.classvariable 和 class.classvariable 有什么区别?
【发布时间】:2017-12-10 06:45:02
【问题描述】:
class demo():
   c_v=[]
   def __init__(self):
       demo.c_v.append('one')

class demo():
   c_v=[]
   def __init__(self):
       self.c_v.append('one')

两者产生相同的结果? 两者的用例是什么?

【问题讨论】:

标签: python class oop variables self


【解决方案1】:

类变量将可供所有从该类创建实例的人使用,就像在类中定义方法一样,而实例变量将仅对该实例可用。

举个例子:

class Example:
   class_i = [1] 
   def __init__(self):
        self.instance_i = [1]

a = Example()
b = Example()
a.class_i.append(2)
b.class_i.append(3)
a.instance_i.append(40)
b.instance_i.append(50)

print a.class_i
print b.class_i
print a.instance_i
print b.instance_i

会给你这个输出:

[1,2,3]
[1,2,3]
[1,40]
[1,50]

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 2018-07-17
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多