Python 中的类扩展就像 Swift 中的那样?

问题描述 投票:0回答:3

我是 python 新手,来自 swift,我想知道以下内容。如果我想快速向现有类添加功能,我可以这样做(如书中示例所示):

extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm

我真的很喜欢这个功能,我想知道Python中是否有类似的东西,或者有其他更好的方法我没有看到,因此这在Python中没有任何意义。

python swift class extension-methods
3个回答
3
投票

为了完整起见,我认为这是你应该做的(也在 Swift 中!):

class Meter(float):
    def to_km(self): return self * 1000.0 
    def to_m (self): return self 
    def to_cm(self): return self / 100.0 
    def to_mm(self): return self / 1000.0 
    def to_ft(self): return self / 3.28084 

oneInch = Meter(25.4).to_mm()
print(oneInch)

明确你的对象代表一米,并且你正在将其转换为某种东西。

如果您想要一些语法糖,我不确定是否有帮助,您可以覆盖项目 getter,这样您就不必使用

()

class Meter(float):
    conversions = {
        'km':1000,
        'cm':.01,
        'mm':.001,
        'ft':1/3.28084
    }
    def __getattr__(self,x):
        try:
            return self*Meter.conversions[x]
        except KeyError:
            raise KeyError("No such conversion!")

oneInch = Meter(25.4).mm
print(oneInch)

添加转换非常简单:

Meter.conversions['whatever'] = 123.123

3
投票

不,您不能扩展内置类,例如

float
int

>>> int.double = lambda self: self * 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'

(虽然你可以修改非内置类,但你真的不应该,因为这样做的代码很难推理。)

pint
这样的单位库可以更好地满足您的特定示例 - 使用这样的库也可以防止您在公制和英制单位之间进行数学计算时犯下 1.25 亿美元的错误。


1
投票
您可以构建父类的子类。如果您正在编写自己的代码,有时这是一个好主意,但扩展诸如 pandas 数据框之类的东西可能是一个坏主意

我没有花太多时间谷歌搜索你,但这是我找到的最好的:

https://docs.python.org/3/tutorial/classes.html

这也是我写的一些非常糟糕的代码,试图向我的女朋友解释类继承。请注意,

Car

 类仍将具有 
car.roll_up_windows()
car.roll_down_windows()
 以及 
__repr__

class Plant(object): def __init__(self, color, seeds): self.color = color self.seeds = seeds class Fruit(Plant): def __init__(self, color, defense): self.color = color self.seeds = True self.defense = defense class Vehicle(object): def __init__(self, num_tires, engine_size, fuel_type): self.num_tires = num_tires self.engine_size = engine_size self.fuel_type = fuel_type self.windows = 'up' def roll_down_windows(self): self.windows = 'down' def roll_up_windows(self): self.windows = 'up' def __repr__(self): print("This is a vehicle. \nIt has {} tires. \nIts engine has {} liters. \nIt runs on {}. \nIt's windows are {}.".format(self.num_tires, self.engine_size, self.fuel_type, self.windows)) class Car(Vehicle): def __init__(self, num_tires=4, engine_size, fuel_type): self.num_tires = num_tires self.engine_size = engine_size self.fuel_type = fuel_type self.windows = 'up'
    
© www.soinside.com 2019 - 2024. All rights reserved.