相关疑难解决方法(0)

什么是在Python中拥有多个构造函数的干净,pythonic方式?

我无法找到明确的答案.AFAIK,你不能__init__在Python类中拥有多个函数.那么我该如何解决这个问题呢?

假设我有一个Cheese使用该number_of_holes属性调用的类.我怎样才能有两种创建奶酪对象的方法......

  1. 一个像这样的洞: parmesan = Cheese(num_holes = 15)
  2. 并且不带参数并且只是随机化number_of_holes属性:gouda = Cheese()

我只想到一种方法来做到这一点,但这似乎有点笨重:

class Cheese():
    def __init__(self, num_holes = 0):
        if (num_holes == 0):
            # randomize number_of_holes
        else:
            number_of_holes = num_holes
Run Code Online (Sandbox Code Playgroud)

你说什么?还有另外一种方法吗?

python constructor

660
推荐指数
9
解决办法
26万
查看次数

在Python中重载int()

假设我在Python 3中有一个基本类,它代表一些类似数字的数据类型.我想这样做,当我有一个这个类的实例,我可以调用int(x)并让它调用我的转换函数来返回整数部分.

我确信这很简单,但我似乎无法找到如何做到这一点.

python class operator-overloading

10
推荐指数
2
解决办法
7532
查看次数

标签 统计

python ×2

class ×1

constructor ×1

operator-overloading ×1