Python - 为什么使用“self"在一个班级? [英] Python - why use "self" in a class?

查看:11
本文介绍了Python - 为什么使用“self"在一个班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个类有何不同?

class A():
    x=3

class B():
    def __init__(self):
        self.x=3

有什么显着差异吗?

推荐答案

A.x 是一个类变量.Bself.x 是一个实例变量.

A.x is a class variable. B's self.x is an instance variable.

Ax 在实例之间共享.

i.e. A's x is shared between instances.

使用可以像列表一样修改的内容来证明差异会更容易:

It would be easier to demonstrate the difference with something that can be modified like a list:

#!/usr/bin/env python

class A:
    x = []
    def add(self):
        self.x.append(1)

class B:
    def __init__(self):
        self.x = []
    def add(self):
        self.x.append(1)

x = A()
y = A()
x.add()
y.add()
print("A's x:", x.x)

x = B()
y = B()
x.add()
y.add()
print("B's x:", x.x)

输出

A's x: [1, 1]
B's x: [1]

这篇关于Python - 为什么使用“self"在一个班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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