我是python的新手,来自swift,我想知道以下几点。在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中没有任何意义。
发布于 2018-08-05 06:14:28
您可以构建父类的子类。如果您正在编写自己的代码,有时这是一个好主意,但是扩展像pandas dataframe这样的东西可能不是一个好主意
我没有花太多时间在谷歌上搜索,但这是我找到的最好的: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'
https://stackoverflow.com/questions/51689856
复制相似问题