Python的类变量和成员变量以及局部变量

Python 专栏收录该内容
152 篇文章 1 订阅

Python的类变量可以通过类和实例名字进行访问而成员变量只能通过实例名来访问,局部变量只能在方法体内被使用。

http://blog.csdn.net/lc_910927/article/details/38757363

类变量和成员变量虽然名字相同但是存储的地址不是相同的。

# -*- coding: utf-8 -*-
class A():
    privatestring="aa"
    def __init__(self,value,privatevalue):
        self.name=value
        self.privatestring=privatevalue
    def change_privatestring(value):
        A.privatestring=value
AAA=A("AA","BB")
print(A.privatestring)
print(AAA.privatestring)
print(A.change_privatestring("CCC"))
print(A.privatestring)
print(AAA.privatestring)
print(A.__dict__)
print(AAA.__dict__)

输出结果:

/usr/bin/python3.5 /home/liusenubuntu/PycharmProjects/sentence/segment/privatelearn.py
aa
BB
None
CCC
BB
{'__module__': '__main__', '__init__': <function A.__init__ at 0x7fb1fefad8c8>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__dict__': <attribute '__dict__' of 'A' objects>, 'change_privatestring': <function A.change_privatestring at 0x7fb1fefadae8>, 'privatestring': 'CCC', '__doc__': None}
----------------------
{'name': 'AA', 'privatestring': 'BB'}

Process finished with exit code 0

类变量是全局变量,一次修改,所有实例化对象的值全部修改
跟Java进行对比:

package classlearn;

public class Node {
    public static int a=1;
}
package classlearn;

public class TestNode {
public static void main(String[] args) {
    Node nodeA=new Node();
    nodeA.a=2;
    System.out.println(nodeA.a);
    Node nodeB=new Node();
    System.out.println(nodeB.a);
    Node nodeC=new Node();
    System.out.println(nodeC.a);
}
}

实验结果:

2
2
2
# -*- coding: utf-8 -*-
class A():
    privatestring="aa"
    def __init__(self,value):
        self.name=value
    def change_privatestring(value):
        A.privatestring=value
AAA=A("AA")
print(A.privatestring)
print(AAA.privatestring)
BBB=A("BB")
A.change_privatestring("BBB")
print(A.privatestring)
print(AAA.privatestring)
print(BBB.privatestring)
print(AAA.change_privatestring("CCC"))

输出结果:

/usr/bin/python3.5 /home/liusenubuntu/PycharmProjects/sentence/segment/privatelearntwo.py
aa
aa
BBB
BBB
BBB
Traceback (most recent call last):
  File "/home/liusenubuntu/PycharmProjects/sentence/segment/privatelearntwo.py", line 16, in <module>
    print(AAA.change_privatestring("CCC"))
TypeError: change_privatestring() takes 1 positional argument but 2 were given

Process finished with exit code 1

普通方法不能被实例化对象调用。

  • 0
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值