获取class类的方法

2025-11-04 23:15:24

1、本文以sublime text3作为示范。

获取class类的方法

2、class Product(object):

pass

首先定义一个类,这里是一个产品类。

获取class类的方法

3、class Product(object):

count = 0

这里设置一个类属性,用于计数。

获取class类的方法

4、class Product(object):

count = 0

@classmethod

这个是定义类方法之前必须要的。

获取class类的方法

5、class Product(object):

count = 0

@classmethod

def total_count(cls):

pass

然后记得参数是cls,因为是类方法。

获取class类的方法

6、class Product(object):

count = 0

@classmethod

def total_count(cls):

print(cls.count)

这样类方法就定义完成了。

获取class类的方法

7、class Product(object):

count = 0

@classmethod

def total_count(cls):

print(cls.count)

def __init__(self, name):

self.name = name

Product.count += 1

然后我们定义一个实例方法,并且调用类属性。

获取class类的方法

8、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()

这里用两个例子来对比类方法的调用,类名+类方法即可。

获取class类的方法

获取class类的方法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢