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 classlevel 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())