【问题标题】:What is the function substituting class member access?替换类成员访问的函数是什么?
【发布时间】:2015-01-02 03:05:23
【问题描述】:

例如,我们有一个类:

class A:
    def __init__(self, a):
        self.a = a

要替换的函数调用是什么:

A.a

我想用map函数来应用它。

【问题讨论】:

  • 你能说得更直白点吗?

标签: python class attributes


【解决方案1】:

你的问题不是很清楚,但是如果你想在 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

【讨论】:

    【解决方案2】:

    class.attribute的功能等效是使用getattr(class, 'attribute')

    >>> class A:
    ...     def __init__(self, a):
    ...         self.a = a
    ...
    >>> obj = A(1)
    >>> obj.a
    1
    >>> getattr(obj, 'a')
    1
    >>>
    

    来自documentation

    getattr(object, name[, default])

    返回object 的命名属性的值。 name 必须是字符串。如果字符串是对象之一的名称 属性,结果是该属性的值。 例如, getattr(x, 'foobar') 等价于x.foobar。如果命名 属性不存在,default 如果提供则返回,否则返回 AttributeError 被提出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2019-10-16
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2015-02-15
      • 2022-01-10
      相关资源
      最近更新 更多