Python class 中的调用方法没有 attribute/got 意外的关键字参数

Python calling method in class has no attribute/got an unexpected keyword argument

我是 Python 的新手,我正在尝试用属性和一种方法定义一个简单的 class。

import scipy.optimize as optimize

class BondPricing:
    
    def __init__(self, price = 95.0428,par = 100,T = 1.5,freq = 2,coup_perc = 5.75,dy = 0.01,guess = 0.05):
        self.price = price
        self.par = par
        self.T = T
        self.freq = freq
        self.coup_perc = coup_perc
        self.dy = dy
        self.guess = guess
        
    def ytm(self):
        freq = float(self.freq) #cast frequency as float data type
        periods = self.T*freq #calculate number of cash flow periods
        coupon = self.coup_perc/100.*self.par/freq #calculate actual periodic coupon level
        dt = [(i+1)/freq for i in range(int(periods))] #calculate time steps in bond maturity
        #write down ytm function from bond pricing formula
        ytm_func = lambda y:sum([coupon/(1+y/self.freq)**(self.freq*t) for t in dt])+self.par/(1+y/self.freq)**(self.freq*self.T)-self.price
        return optimize.newton(ytm_func, self.guess) #find root of ytm function via Newton-Raphson 


bond1 = BondPricing()

当我尝试用 bond1.ytm(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2) 调用 class 的方法时,出现以下错误:

TypeError: ytm() got an unexpected keyword argument 'price'

或者当我尝试时:

bond1.ymt()

我收到这个错误:

AttributeError: 'BondPricing' object has no attribute 'ymt'

谁能解释一下我做错了什么?

非常感谢!

When I try to call the method of the class with bond1.ytm(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2), I get the following error:

TypeError: ytm() got an unexpected keyword argument 'price'

错误是因为 ytm 方法不接受任何参数。 你应该在初始化 class 时传递参数。 示例:

    bond1 = BondPricing(price = 95.0428, par = 100, T = 1.5, coup_perc = 5.75, freq = 2)
    # now call ytm method on the object
    bond1.ytm()

or when I try: bond1.ymt() I get this error:

AttributeError: 'BondPricing' object has no attribute 'ymt'

您已将方法名称定义为ytm。 你应该称它为

bond1.ytm() # not bond1.ymt()