如何添加方法属性?
How to add a method attribute?
是否可以将方法属性添加到 python class:
# something similar to this perhaps:
p.new_salary_getter = lambda(self, i) { return self.salaries[i] }
这是一个完整的示例上下文:
class Person:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
p = Person("oren", 28)
for i in range(12):
if hasattr(p, "salaries"):
salaries = getattr(p, "salaries")
salaries[i] = 1000*i
else:
p.salaries = {i: 1000*i}
def getter(i: int) -> int:
return self.salaries[i]
p.get_salary = getter
p.get_salary(7)
我得到的错误:
Traceback (most recent call last):
File "main.py", line 18, in <module>
p.get_salary(7)
File "main.py", line 15, in getter
return self.salaries[i]
NameError: name 'self' is not defined
由于您现在正在定义自己的函数而不是使用 lambda
,我将切换到该策略。
这是一些代码,'works' 其中 class 稍后添加了一个方法:
class Person:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
p = Person("oren", 28)
p.salaries = [1,2,3]
def getter(self, i: int) -> int:
return self.salaries[i]
Person.get_salary = getter
print(p.get_salary(0))
输出:
1
TLDR lambda 样式:
Person.get_salary = lambda self, i: self.salaries[i]
未来的我:你错过了 Person.
和 lambda
而没有 return
是否可以将方法属性添加到 python class:
# something similar to this perhaps:
p.new_salary_getter = lambda(self, i) { return self.salaries[i] }
这是一个完整的示例上下文:
class Person:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
p = Person("oren", 28)
for i in range(12):
if hasattr(p, "salaries"):
salaries = getattr(p, "salaries")
salaries[i] = 1000*i
else:
p.salaries = {i: 1000*i}
def getter(i: int) -> int:
return self.salaries[i]
p.get_salary = getter
p.get_salary(7)
我得到的错误:
Traceback (most recent call last):
File "main.py", line 18, in <module>
p.get_salary(7)
File "main.py", line 15, in getter
return self.salaries[i]
NameError: name 'self' is not defined
由于您现在正在定义自己的函数而不是使用 lambda
,我将切换到该策略。
这是一些代码,'works' 其中 class 稍后添加了一个方法:
class Person:
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
p = Person("oren", 28)
p.salaries = [1,2,3]
def getter(self, i: int) -> int:
return self.salaries[i]
Person.get_salary = getter
print(p.get_salary(0))
输出:
1
TLDR lambda 样式:
Person.get_salary = lambda self, i: self.salaries[i]
未来的我:你错过了 Person.
和 lambda
而没有 return