English 中文(简体)
Can 我有两个论点。
原标题:Can I have two sets of arguments

I am trying to make a dice roller in python. the code is:

class die:
    def __init__(self, num:int, die:int | str, mod:int=0, keep:int=None):
        keep = keep if keep != None else num
        if keep > num:  keep = num
        self.num, self.die, self.mod, self.keep = num, die, mod, keep
    def __repr__(self) -> str:
        mod = f"+{self.mod}" if self.mod > 0 else f"-{abs(self.mod)}" if self.mod < 0 else   
        keep = f"{f"{self.keep}kh" if self.keep > 0 else f"{abs(self.keep)}kl" if self.keep < 0 else   }"
        return f"{keep}{self.num}d{self.die}{mod}"
    def roll(self) -> int:
        log = []
        die = range(0, self.num)
        for _ in die:
            log += [rand.randint(0, (10 if self.die ==  %  else int(self.die)) * (10 if self.die ==  %  else 1))]
        if self.keep > 0:
            log = [log] + [heapq.nlargest(self.keep, log)]
        elif self.keep < 0:
            log = [log] + [heapq.nsmallest(abs(self.keep), log)]
        final = sum(log[1], self.mod)
        return final
#Sorry if my code is hard to read.

我想增加通过小话语(实例:4d6+3)的能力以及各种选择。 如果只有一个论点,我就能够单独提出论点。 例如:

def __init__(self, num:int, die:int | str, mod:int=0, keep:int=None OR expression:str)
问题回答

http://www.un.org/Depts/DGACM/index_french.htm 将体格划分为适当论据的工作,应以}/em>方法处理。

类似于

class die:
    def __init__(self, num:int, die:int | str, mod:int=0, keep:int=None):
        ...

    @classmethod
    def from_description(cls, descr: str) -> die:
        num, die, mod = re.match("d+dd++d+").groups()
        return cls(num, die, mod)

d = die.from_description("4d6+3")

戴维的实施工作使用简单的等效法来匹配对方法签名的论点,因此不支持诸如<条码>、int > >>>> >等复合类说明,因此,我接着使用优异的操作型核对器 警卫/编码>::

import types
from typeguard import typechecked

class MultiMethod:
    def __init__(self, name):
        self._methods = []
        self.__name__ = name

    def register(self, method):
        self._methods.append(typechecked(method))

    def __call__(self, *args, **kwargs):
        for method in self._methods:
            try:
                return method(*args, **kwargs)
            except TypeError:
                pass
        raise TypeError(f No matching method )

    def __get__(self, instance, cls):
        if instance is not None:
            return types.MethodType(self, instance)
        return self

class MultiDict(dict):
    def __setitem__(self, key, value):
        if key in self:
            current_value = self[key]
            if isinstance(current_value, MultiMethod):
                current_value.register(value)
            else:
                mvalue = MultiMethod(key)
                mvalue.register(current_value)
                mvalue.register(value)
                super().__setitem__(key, mvalue)
        else:
            super().__setitem__(key, value)

class Overloadable(type):
    def __new__(cls, clsname, bases, clsdict):
        return type.__new__(cls, clsname, bases, dict(clsdict))

    @classmethod
    def __prepare__(cls, clsname, bases):
        return MultiDict()

因此:

import re

class die(metaclass=Overloadable):
    def __init__(self, num: int, die: int | str, mod: int = 0):
        self.num = num
        self.die = die
        self.mod = mod

    def __init__(self, expression: str):
        self.__init__(*map(int, re.match(r (d+)d(d+)+(d+) , expression).groups()))

print(vars(die( 4d6+3 )))

产出:

{ num : 4,  die : 6,  mod : 3}

Demo:





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...