版权声明:个人原创,所属@jerry 本人 https://blog.csdn.net/qq_42938842/article/details/84145539
普通方法, 类方法 classmethod 与 静态方法staticmethod 使用和区别.属性函数property特性
类方法: 使用时使用classmethod装饰器装饰的方法
优点: 简洁的创建对象
对外提供简单易懂的接口, 利用cls属性接口示例:
class Number:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return self.num1 + self.num2
def sub(self):
return self.num1 - self.num2
def mul(self):
return self.num1 * self.num2
def div(self):
if self.num2 == 0:
return None
return self.num1 / self.num2
# 对外提供简单易用的接口
@classmethod
def pingfanghe(cls, num1, num2):
n1 = cls(num1, num1)
n12 = n1.mul()
n2 = cls(num2, num2)
n22 = n2.mul()
n3 = cls(n12, n22)
return n3.add()
he = Number.pingfanghe(3, 4)
print(he)
静态方法: 使用staticmethod
装饰器装饰的方法(方法没有cls参数)
对于普通方法
当实例调用时,默认将当前实例传进去
类调用时,只能以 类名.method(类实例) 形式调用
总结:
凡是静态方法完成的功能都可以是类方法完成
若方法中没有使用到类名(cls),可以使用静态方法
property 的特性示例:
作用: 保护特定属性,或者对特定属性进行处理
class User:
def __init__(self, username, password):
self.username = username
self.__password = password
# 该方法可以像成员属性一样访问
@property
def password(self):
print('有人想查看密码')
# return '想偷看密码,没门'
return self.__password
# 在设置密码时,会自动调用
@password.setter
def password(self, password):
print('@password.setter', password)
self.__password = '加密' + password + '加密'
u = User('xiaoming', '111111')
#
print(u.password)
#
# # 设置密码,会自动调用setter方法
u.password = 'abcde'
print(u.password)