直接上代码:
class Example(object):
count = 0#类属性,存在类是的空间里面
def __init__(self,data1,data2):
self.__data1=data1
self.data2=data2
Example.count+=1#你可以直接通过类名点的方式获取类的属性
print(id(self),id(Example))
def __func1(self):
print("Example类的私有方法可以被调用!")
print(id(self),id(Example))
def show_data(self):
self.__func1()
print(self.__data1)
print(self.data2)
@classmethod #以为则不需要self了,因为这个方法属于类,他不属于具体的实例,所以参数变成cls,cls就代表当前类
def Exp(cls):
print('现在你已经创建了%d个对象'%cls.count)
@staticmethod#加上一个语法糖即可,调用方式也是通过类名点的形式
def sta():
print('你好,我还静态方法,说白了我只是一个广义的封装,简单的把在外面可以运行的函数拿到类里面来了,其他的不变')
exp= Example(50,100)
exp.show_data()
![](https://img.haomeiwen.com/i20557576/66d016c79ed59ffa.png)
![](https://img.haomeiwen.com/i20557576/b5889e1ca3bff658.png)
![](https://img.haomeiwen.com/i20557576/a78666acadcd40ef.png)
网友评论