Class methods accessing class attributes
- @classmethod
"total" is an attribute that belongs to the class. We can access it using Date.total. We can create a @classmethod
to access it,
but actually we can access it from the outside even without the class method, just using the "class object"
class Date:
total = 0
def __init__(self, Year, Month, Day):
self.year = Year
self.month = Month
self.day = Day
Date.total += 1
def __str__(self):
return 'Date({}, {}, {})'.format(self.year, self.month, self.day)
def set_date(self, y, m, d):
self.year = y
self.month = m
self.day = d
@classmethod
def get_total(class_object):
print(class_object)
return class_object.total
from mydate import Date
d1 = Date(2013, 11, 22)
print(d1)
print(Date.get_total())
print(Date.total)
print('')
d2 = Date(2014, 11, 22)
print(d2)
print(Date.get_total())
print(Date.total)
print('')
d1.total = 42
print(d1.total)
print(d2.total)
print(Date.get_total())
print(Date.total)
Date(2013, 11, 22)
<class 'mydate.Date'>
1
1
Date(2014, 11, 22)
<class 'mydate.Date'>
2
2
42
2
<class 'mydate.Date'>
2
2