小编use*_*139的帖子

插入数据后更改类的类类型

我想在python中创建一个类,它应该像这样工作:

  1. 分配的数据,可能绑定到变量(例如a = exampleclass(data)或只是exampleclass(data))

  2. 插入数据后,它应自动确定数据的某些属性,如果某些属性已满,则会自动...

  3. ...将班级改为另一班级

第3部分是我遇到问题的部分.我如何真正改变班级内的课程?例如:

如果我有两个班,一个是Small_Numbers,另一个是Big_numbers; 现在我希望任何small_number小于1000的转移到a Big_number,反之亦然,testcode:

a = Small_number(50)
type(a) # should return Small_number.
b = Small_number(234234)
type(b) # should return Big_number.
c = Big_number(2)
type(c) # should return Small_number.
Run Code Online (Sandbox Code Playgroud)

这可能吗?

python class python-3.x

8
推荐指数
3
解决办法
8794
查看次数

使用radd方法在类之间添加

class exampleclass1:
    def __init__(self, data):
        self.data = data

    def __add__(self, other):
        if isinstance(other, int):
            print('blabla')


class exampleclass2:
    def __init__(self, data):
        self.data = data

    def __add__(self, other):
        if isinstance(other, exampleclass1):
            print("it's working yay")

    __radd__ = __add__

a = exampleclass1('q')

b = exampleclass2('w')

a+b
Run Code Online (Sandbox Code Playgroud)

我的问题是:我有两个不同的类,我想在一个类中定义它们的添加,并为该类定义add和radd(在这个例子中是exampleclass2.我不想创建一个add方法适用于exampleclass1以添加exampleclass2.

就像现在一样,它只是忽略了它.我也试图提出错误,但这也没有用.非常高兴能得到我的帮助!:)

python-3.x

4
推荐指数
3
解决办法
8395
查看次数

标签 统计

python-3.x ×2

class ×1

python ×1