【Python入门自学笔记专辑】——面向对象编程——类方法-静态方法

面向对象编程——类方法-静态方法-装饰器

类方法

“类方法”与“类变量”类似属于类。

定义类方法实例代码如下:

class Account:
    """定义银行账户类"""
    
    interest_rate = 0.0668
    
    def __init__(self, owner, amount):
        self.owner = owner # 定义实例变量账户名
        self.amount = amount # 定义实例变量账户金额
        pass
    
    # 类方法
    @classmethod
    def interest_by(cls, amt):
        return cls.interest_rate * amt
   	pass
interest = Account.interest_by(12_000.0)
print('计算利息:{0:.4f}'.format(interest))

运行结果

计算利息:801.6000

程序第十二行有一句@classmethod,意思是声明该方法为类方法

提示:装饰器(Decorators)是Python3.0之后加入的新特性,以@开头修饰函数、方法和类,用来修饰和约数它们,类似于Java中的注解。

静态方法

如果定义的方法既不想与实例绑定,也不想与类绑定,只是想把类作为他的命名空间,那么可以定义静态方法

实例:

class Account:
    """定义银行账户类"""
    
    interest_rate = 0.0668
    
    def __init__(self, owner, amount):
        self.owner = owner
        self.amount = amount
     	pass
    
    # 类方法
    @classmethod
    def interest_by(cls, amt):
        return cls.interest_rate * amt
    
    # 静态方法
    @staticmethod
    def interest_with(amt):
        return Account.interest_by(amt)
    
interest1 = Account.interest_by(12_000.0)
print("计算利息:{0:.4f}".format(interest1))
interest2 - Account.interest_with(12_000.0)
print("计算利息:{0:.4f}".format(interest2))
posted @ 2020-04-11 16:21  Aeterna_Gungnir  阅读(113)  评论(0编辑  收藏  举报