替代class会员权限的功能是什么?
What is the function substituting class member access?
比如我们有一个class:
class A:
def __init__(self, a):
self.a = a
要替换的函数调用是什么:
A.a
我想用 map
函数来应用它。
你的问题不是很清楚,但是如果你想改变python中A.a
的值,很简单
A.a = "New Value"
根据我从 python documentation 中读到的内容,您似乎可以像其他语言一样不需要 setter() 和 getter() 函数就可以做到这一点。我从上面的 link hyperlinked 中获取了这个例子。
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])
Return the value of the named attribute of object
. name
must be a string. If the string is the name of one of the object’s
attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar')
is equivalent to x.foobar
. If the named
attribute does not exist, default
is returned if provided, otherwise
AttributeError
is raised.
比如我们有一个class:
class A:
def __init__(self, a):
self.a = a
要替换的函数调用是什么:
A.a
我想用 map
函数来应用它。
你的问题不是很清楚,但是如果你想改变python中A.a
的值,很简单
A.a = "New Value"
根据我从 python documentation 中读到的内容,您似乎可以像其他语言一样不需要 setter() 和 getter() 函数就可以做到这一点。我从上面的 link hyperlinked 中获取了这个例子。
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])
Return the value of the named attribute of
object
.name
must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,getattr(x, 'foobar')
is equivalent tox.foobar
. If the named attribute does not exist,default
is returned if provided, otherwiseAttributeError
is raised.