类方法:
@classmethod
添加classmethod的方法,即类方法,无法访问实例中的变量。
例:
class Animal(object):
def __init__(self, name):
self.name = name
@classmethod
def talk(self):
print('%s is talking...' % self.name)
d = Animal('Ivien')
d.talk()
# Traceback (most recent call last):
# File "D:/python/oldboy/DAY07/CPRAC.py", line 11, in <module>
# d.talk()
# File "D:/python/oldboy/DAY07/CPRAC.py", line 7, in talk
# print('%s is talking...' % self.name)
# AttributeError: type object 'Animal' has no attribute 'name'
#
# Process finished with exit code 1
静态方法
@staticmethod
添加了@staticmethod的方法为静态方法,既无法访问类变量也无法访问实例变量。
例:
class Animal(object):
def __init__(self, name):
self.name = name
@staticmethod
def walk(self):
print('%s is walking ...' % self.name)
d = Animal('Ivien')
d.walk()
# Traceback (most recent call last):
# File "D:/python/oldboy/DAY07/CPRAC.py", line 9, in <module>
# d.walk()
# TypeError: walk() missing 1 required positional argument: 'self'
属性
@property
将方法转换为属性
例:
class Animal(object):
def __init__(self, name):
self.name = name
animal_number = 9
@property
def count(self):
print('There are %s ' % Animal.animal_number)
@count.setter
def count(self, ani_num):
Animal.animal_number = ani_num
print('ani_num :', Animal.animal_number)
@count.deleter
def count(self):
del Animal.animal_number
print('animal_number deleted')
d = Animal('Ivien')
d.count
d.count = 3
d.count
del d.count
# There are 9
# ani_num : 3
# There are 3
# animal_number deleted
print(d.count)
# Traceback (most recent call last):
# File "D:/python/oldboy/DAY07/CPRAC.py", line 28, in <module>
# print(d.count)
# File "D:/python/oldboy/DAY07/CPRAC.py", line 9, in count
# print('There are %s ' % Animal.animal_number)
# AttributeError: type object 'Animal' has no attribute 'animal_number'