zoukankan      html  css  js  c++  java
  • 【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))
    
  • 相关阅读:
    HTML 网页创建
    CSS3 opacity
    两数相加的和
    九九乘法表
    Linux下的Makefile初入
    linux 下定义寄存器宏 实现类似于STM32的寄存器操作
    Linux 编译与交叉编译
    linux IMX6 汇编点亮一个LED灯
    Linux基本指令与作用
    C# Task 源代码阅读(2)
  • 原文地址:https://www.cnblogs.com/coding365/p/12872236.html
Copyright © 2011-2022 走看看