电脑现已成为我们工作、生活和娱乐必不可少的工具了,在使用电脑的过程中,可能会遇到获取class类的方法的问题,如果我们遇到了获取class类的方法的情况,该怎么处理怎么才能解决...
电脑现已成为我们工作、生活和娱乐必不可少的工具了,在使用电脑的过程中,可能会遇到获取class类的方法的问题,如果我们遇到了获取class类的方法的情况,该怎么处理怎么才能解决获取class类的方法带来的困扰呢,对于这样的问题其实我们只需要python3本文以sublime text3作为示范。class Product(object):pass首先定义一个类,这里是一个产品类。class Product(object):count = 0这里设置一个类属性,用于计数。class Product(object):count = 0@classmethod这个是定义类方法之前必须要的。class Product(object):cou这样就解决了这样的问题,接下来给大家带来获取class类的方法的详细操作步骤。
工具/原料
python3
方法/步骤
本文以sublime text3作为示范。

class Product(object):
pass
首先定义一个类,这里是一个产品类。

class Product(object):
count = 0
这里设置一个类属性,用于计数。

class Product(object):
count = 0
@classmethod
这个是定义类方法之前必须要的。

class Product(object):
count = 0
@classmethod
def total_count(cls):
pass
然后记得参数是cls,因为是类方法。

class Product(object):
count = 0
@classmethod
def total_count(cls):
print(cls.count)
这样类方法就定义完成了。

class Product(object):
count = 0
@classmethod
def total_count(cls):
print(cls.count)
def __init__(self, name):
self.name = name
Product.count += 1
然后我们定义一个实例方法,并且调用类属性。

class Product(object):
count = 0
@classmethod
def total_count(cls):
print(cls.count)
def __init__(self, name):
self.name = name
Product.count += 1
pen = Product("Pen")
phone = Product("Phone")
key = Product("Key")
Product.total_count()
这里用两个例子来对比类方法的调用,类名+类方法即可。


注意事项
类方法,静态方法两者的书写是有区别的
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

