我创建了两个返回已排序列表的函数.它们都作为参数列出了包含Employee Class实例的列表.第一个按名称属性排序,第二个按年龄排序,两者都使用lambda函数
class Employee():
allEmployees = []
def __init__(self, name, age):
self.name = name
self.age = age
Employee.allEmployees.append(self)
def sortEmployeesByName(some_list, name):
return sorted(some_list, key=lambda employee: employee.name)
def sortEmployeesByAge(some_list, age):
return sorted(some_list, key=lambda employee: employee.age)
Run Code Online (Sandbox Code Playgroud)
如何只创建一个函数sortEmployees,我将属性作为第二个参数传递,并使用lambda函数?
例如
def sortEmployess(some_list, attribute):
return sorted(some_list, key=lambda employee: employee.attribute)
Run Code Online (Sandbox Code Playgroud) 我有一段使用类变量的代码.我已经读过Ruby中通常应该避免使用类变量.
类变量是@@cost和@@kwh.
如何在不使用类变量的情况下重写以下内容?
class Device
attr_accessor :name, :watt
@@cost = 0.0946
def initialize(name, watt)
@name = name
@watt = watt
end
def watt_to_kwh(hours)
@@kwh = (watt / 1000) * hours
end
def cost_of_energy
puts "How many hours do you use the #{self.name} daily?"
hours = gets.chomp.to_i
self.watt_to_kwh(hours)
daily_cost = @@kwh * @@cost
montly_cost = daily_cost * 30
puts "Dayly cost: #{daily_cost}€"
puts "montly_cost: #{montly_cost}€"
end
end
Run Code Online (Sandbox Code Playgroud)