类方法和静态方法的实现
# 类方法和静态方法的实现
class contact:
all_contacted = []
# 类属性,所有实例可更改,当然也相同值的属性
def __init__(self, name, phone_num, sex):
self.name = name
self.phone_num = phone_num
self.sex = sex
contact.all_contacted.append(self)
# 下面是通过类方法和静态方法实现对名字的搜索
@classmethod
def search(cls, nameing):
# 定义一个类方法
# 类方法要用一个cls作为调用的对象
return [con.name for con in contact.all_contacted if nameing in con.name]
@staticmethod
def staticway(a, b):
print([con.name for con in a if b in con.name])
contact_one = contact("suanA", 134556, "male")
contact_two = contact("suanB", 3245432, "female")
contact_three = contact("johnA", 23234, "male")
contact_four = contact("johnB", 23234, "male")
print(contact.search("john"))
print(contact.staticway(contact.all_contacted, "suan"))
关于提醒的是,python3中静态方法和类方法不是必要使用装饰器