You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Samadateconverter类方法报错:gregorian_to_hijri需1参却传3参

问题解决:gregorian_to_hijri() takes 1 positional argument but 3 were given

错误原因

gregorian_to_hijri是实例方法,这类方法默认第一个参数是self(指向类的实例),但你直接通过类名Samadateconverter调用它,同时传入1233,5,7三个参数,相当于给方法传了4个参数(含隐式的self),和方法定义的参数数量不匹配,因此触发报错。

解决方法

方法1:创建类实例后调用方法

这是最贴合当前类设计的方式,因为你的类通过__init__接收日期参数并存储为实例属性,实例方法依赖这些属性运行:

from class_converter import Samadateconverter

# 先创建实例,传入日期参数
converter = Samadateconverter(1233, 5, 7)
# 通过实例调用转换方法
result = converter.gregorian_to_hijri()
print(result)

方法2:将方法改为类方法/静态方法

如果不想创建实例,可修改方法定义,让它直接接收日期参数:

改为类方法(使用@classmethod装饰器)

class Samadateconverter:
    def __init__(self, y , m , d ):
        self.y = y
        self.m = m
        self.d = d
                 
    @classmethod
    def gregorian_to_hijri(cls, y, m, d):
        # 直接使用传入的y、m、d计算,不再依赖self属性
        jdn = int((1461 * (y + 4800 + int((m - 14) / 12))) / 4) + int((367 * (m - 2 - 12 * int((m - 14) / 12))) / 12) - int((3 * int((y + 4900 + int((m - 14) / 12)) / 100)) / 4) + d - 32075

        h = int((jdn - 1948440 + 10632) / 10631)
        year = int((h + 10307) / 1335)
        month = ((h - 1) % 12) + 1
        day = jdn - 1948440 - int((year * 354) + int((3 + (11 * year)) / 30)) - int((month - 1) * 29.5) + 1

        return (year, month, day)

调用方式和你原来的写法一致:

from class_converter import Samadateconverter

result = Samadateconverter.gregorian_to_hijri(1233, 5, 7)
print(result)

改为静态方法(使用@staticmethod装饰器)

逻辑和类方法类似,只是不需要cls参数:

class Samadateconverter:
    def __init__(self, y , m , d ):
        self.y = y
        self.m = m
        self.d = d
                 
    @staticmethod
    def gregorian_to_hijri(y, m, d):
        # 直接使用传入的参数计算
        jdn = int((1461 * (y + 4800 + int((m - 14) / 12))) / 4) + int((367 * (m - 2 - 12 * int((m - 14) / 12))) / 12) - int((3 * int((y + 4900 + int((m - 14) / 12)) / 100)) / 4) + d - 32075

        h = int((jdn - 1948440 + 10632) / 10631)
        year = int((h + 10307) / 1335)
        month = ((h - 1) % 12) + 1
        day = jdn - 1948440 - int((year * 354) + int((3 + (11 * year)) / 30)) - int((month - 1) * 29.5) + 1

        return (year, month, day)

调用方式不变:

from class_converter import Samadateconverter

result = Samadateconverter.gregorian_to_hijri(1233, 5, 7)
print(result)

总结

  • 若需复用同一日期做多次转换,优先用方法1创建实例;
  • 若仅单次转换且不想创建实例,用方法2的类方法或静态方法更便捷。

内容的提问来源于stack exchange,提问作者Sajjad Mahmeody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 23:55:34