Python class variable、class method

本文深入探讨了类变量和类方法的概念,解释了它们如何在类的所有实例间共享信息,以及如何通过类方法访问这些变量,实现对类级别信息的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A class variable is a variable associated with a class, not an instance of a class, and is accessible by all instances of the class. A class variable might be used to keep track of some class­level information, such as how many instances of the class have been created at any point.

 

# Class methods are similar to static methods in that they can be invoked before an object of the class has been instantiated or by using an instance of the class. But class methods are implicitly passed the class they belong to as their first parameter, so you can code them more simply
# By using a class method instead of a static method, you don’t have to hardcode the class name into total_area. As a result, any subclasses of Circle can still call total_area and refer to their own members, not those in Circle.


class Circle:
    """Circle class"""
    # Variable containing a list of all circles which have been created.
    all_circles = []  # class variable
    pi = 3.14159

    def __init__(self, r=1):
        """Create a Circle with the given radius"""
        self.radius = r
        self.__class__.all_circles.append(self)# 在instance method里解除class variable的方法示例self.__class__.pi

    def area(self):
        """determine the area of the Circle"""
        return self.__class__.pi * self.radius * self.radius
        # return self.radius * self.radius * Circle.pi
#         one may object to hardcoding the name of a class inside that class’s methods. You can
# avoid doing so through use of the special __class__ attribute

    @classmethod#也多半是关系到类级别的操作才用classmethod
    def total_area(cls):

        total = 0
        for c in cls.all_circles:
            total = total + c.area()
        return total


c = Circle(3)
print(c.area())
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值