类属性和类方法
- 类属性就是给类对象中定义的属性
- 类属性记录与类相关的信息
class Tool(object):
#使用赋值语句定义类属性 记录所有的工具对象
cout=0
def __init__(self,name):
self.name=name
#类属性+1
Tool.cout+=1
gj1=Tool('hello')
gj2=Tool('word')
#打印创建对象的个数
print(Tool.cout)
调用类属性的两种方式:
- 类名.类属性
- 对象.类属性(不推荐使用)
类方法和实例方法的区别?
类方法的定义格式:
@classmethod
class A(cls) :
PASS
类方法案例
class Tool(object):
#1.定义一个类属性
count=0
def __init__(self,name):
self.name=name
Tool.count+=1
#2.定义一个类方法
@classmethod
def count_with(cls):
print('创建工具的数量为%s'%cls.count)
#创建工具对象
tool1=Tool('刀锋')
tool2=Tool('深蓝')
#用类对象调用类方法
Tool.count_with()
静态方法:不需要访问实例属性 也不需要访问类属性的方法
案例:
class Dog(object):
def __init__(self,name):
self.name=name
#定义静态方法
@staticmethod
def run():
print('runrurnun')
tg=Dog('jjjj')
#静态方法的调用
Dog.run()