【发布时间】:2015-01-02 03:05:23
【问题描述】:
例如,我们有一个类:
class A:
def __init__(self, a):
self.a = a
要替换的函数调用是什么:
A.a
我想用map函数来应用它。
【问题讨论】:
-
你能说得更直白点吗?
标签: python class attributes
例如,我们有一个类:
class A:
def __init__(self, a):
self.a = a
要替换的函数调用是什么:
A.a
我想用map函数来应用它。
【问题讨论】:
标签: python class attributes
你的问题不是很清楚,但是如果你想在 python 中更改A.a 的值,那么简单
A.a = "New Value"
从我从python documentation 中读到的内容看来,您无需像其他语言那样使用 setter() 和 getter() 函数就可以做到这一点。我从上面的超链接链接中获取了这个示例。
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
【讨论】:
做class.attribute的功能等效是使用getattr(class, 'attribute'):
>>> class A:
... def __init__(self, a):
... self.a = a
...
>>> obj = A(1)
>>> obj.a
1
>>> getattr(obj, 'a')
1
>>>
getattr(object, name[, default])返回
object的命名属性的值。name必须是字符串。如果字符串是对象之一的名称 属性,结果是该属性的值。 例如,getattr(x, 'foobar')等价于x.foobar。如果命名 属性不存在,default如果提供则返回,否则返回AttributeError被提出。
【讨论】: