理解java和python类变量以及类的成员变量
作者:Shy泠 时间:2023-09-14 19:42:55
最可怕的不是犯错而是一直都没发现错误,直到现在我才知道自己对类变量的理解有问题。
大概可能也许是因为不常用类变量的原因吧,一直没有发现这个问题。最近在看C++时才知道了类变量到底是什么?
以前我一直觉得类变量和成员变量的唯一区别是类变量可以通过类名直接访问,是静态的。而成员变量需要实例化一个类后通过实例来访问。
万万没想到忽视了类变量在一个类中只有一个,各个实例中的都是同一个的,在一个实例中修改会影响其他实例中的类变量...(虽然平常也没有因为这个而引起什么bug,但是还是要补上认知的漏洞)。
这里有用java和python写的2个例子:
public class OO{
public static String s;
public String m;
static{
s = "Ever";
}
public static void main(String[] args){
OO o1 = new OO();
OO o2 = new OO();
o1.m = "Once";
//不同实例中的类变量值/地址相同
System.out.println(o1.s);
System.out.println(o2.s);
System.out.println(o1.s.hashCode());
System.out.println(o2.s.hashCode());
o1.s = "123";
System.out.println(o2.s);//更改类变量后影响了其他实例
System.out.println(o1.m.hashCode());
System.out.println(o2.m.hashCode());//NullPointerException
//成员变量具有不同的地址
}
}
#!/bin/python
class B:
def whoami(self):
print("__class__:%s,self.__class__:%s"%(__class__,self.__class__))
class C(B):
count = 0
def __init__(self):
super(C,self).__init__()
self.num = 0
def add(self):
__class__.count += 1
self.num += 1
def print(self):
print("Count_Id:%s,Num_Id:%s"%(id(__class__.count),id(self.num)))
print("Count:%d,Num:%d"%(__class__.count,self.num))
i1 = C()
i2 = C()
i1.whoami()
i2.whoami()
#i1的成员变量增加了1次,i2的成员变量增加了2次,类变量共增加了3次
i1.add()
i2.add()
i2.add()
i1.print()
i2.print()
标签:java,python,类,变量
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
android开发教程之view组件添加边框示例
2023-05-24 17:16:44
WinForm项目开发中Excel用法实例解析
2022-07-11 10:23:03
![](https://img.aspxhome.com/file/2023/2/108622_0s.png)
Java线程安全中的原子性浅析
2021-09-06 16:08:13
![](https://img.aspxhome.com/file/2023/0/67960_0s.png)
Java多线程之Semaphore实现信号灯
2023-09-19 23:04:51
C#中Task.Yield的用途深入讲解
2022-11-12 00:16:23
Java详解实现多线程的四种方式总结
2023-04-04 19:43:34
![](https://img.aspxhome.com/file/2023/8/71138_0s.png)
Android中Edittext设置输入条件
2023-03-11 23:05:08
一文了解Java读写锁ReentrantReadWriteLock的使用
2023-10-12 19:28:21
![](https://img.aspxhome.com/file/2023/7/63067_0s.jpg)
Java编程复用类代码详解
2021-09-13 10:06:34
关于报错IDEA Terminated with exit code 1的解决方法
2021-06-03 08:33:12
![](https://img.aspxhome.com/file/2023/4/116834_0s.png)
Intellij IDEA 2017新特性之Spring Boot相关特征介绍
2023-06-22 15:13:02
![](https://img.aspxhome.com/file/2023/0/88140_0s.gif)
Android实现简单的banner轮播图
2021-10-25 01:11:28
![](https://img.aspxhome.com/file/2023/4/117174_0s.jpg)
C#将PDF转为多种图像文件格式的方法(Png/Bmp/Emf/Tiff)
2022-06-29 16:13:03
![](https://img.aspxhome.com/file/2023/9/74819_0s.jpg)
Java源码解析之接口List
2022-06-13 08:46:44
![](https://img.aspxhome.com/file/2023/4/122284_0s.png)
SpringDataJPA在Entity中常用的注解介绍
2023-11-27 09:40:36
java比较器Comparable接口与Comaprator接口的深入分析
2022-01-20 11:51:09
Java 滑动窗口最大值的实现
2021-09-10 15:34:20
![](https://img.aspxhome.com/file/2023/2/121432_0s.png)
java使用stream判断两个list元素的属性并输出方式
2023-02-06 14:15:18
查找算法之二分查找的C++实现
2022-05-27 07:24:17
浅谈Java中的n种随机数产生办法
2023-12-22 10:36:29