【问题标题】:how to use instance attribute to define a class attribute?如何使用实例属性来定义类属性?
【发布时间】:2017-03-12 12:14:47
【问题描述】:

我正在尝试将 init 中的名称用于我的类属性 attr,但这似乎是不可能的。 这是代码:

class B:

    def __init__(self, val):
        self.val = val

    def __get__(self, instance, owner):
        return owner.valEditNew(self.val)

    def __set__(self, instance, value):
        return


class A:

    def __init__(self, name = 'def_name'):
        self.name = name

    attr = B('G120')

    def valEditNew(val):
        val += ' @edited'
        return val

a = A('JJ')
print(a.attr)

如果我使用 self.name 或 name 或 ... 代替 G120>>> builtins.NameError: name 'self' is not defined 如果这不可能,你能给我指路吗?

【问题讨论】:

    标签: python python-3.x class attributes


    【解决方案1】:

    如果要访问包含描述符对象的实例的属性,请使用__get__/__set__instance参数:

    class B:
    
        def __get__(self, instance, owner):
            return instance.valEditNew(instance.name)  # <---
    
        def __set__(self, instance, value):
            return
    
    
    class A:
    
        attr = B()
    
        def __init__(self, name='def_name'):
            self.name = name
    
        def valEditNew(self, val):
            val += ' @edited'
            return val
    
    
    a = A('JJ')
    print(a.attr)
    # prints => JJ @edited
    

    【讨论】:

    猜你喜欢
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多