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

编程知识 行业动态 更新时间:2024-06-13 00:20:42

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

类方法

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

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

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))

更多推荐

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

本文发布于:2023-03-30 10:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/5f8832c8c2cf82fa1c70189d103de09f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   静态   面向对象   入门   笔记

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!