小编Nag*_*aga的帖子

在python中访问超(父)类变量

我是python的新手。我试图使用 super() 方法访问子类中的父类变量,但它抛出错误“无参数”。使用类名访问类变量有效,但我想知道是否可以使用 super() 方法访问它们。

class Parent(object):
        __props__ = (
            ('a', str, 'a var'),
            ('b', int, 'b var')
        )

        def __init__(self):
            self.test = 'foo'

class Child(Parent):
    __props__ = super().__props__ + (
        ('c', str, 'foo'),
    ) # Parent.__props__


    def __init__(self):
        super().__init__()
Run Code Online (Sandbox Code Playgroud)

错误:

    __props__ = super().__props__ + (
RuntimeError: super(): no arguments
Run Code Online (Sandbox Code Playgroud)

python class python-3.x

8
推荐指数
1
解决办法
8580
查看次数

3.6 之前的 Python 版本中没有 __set_name__ 的解决方法

在Python 3.6中,我可以使用__set_name__钩子来获取描述符的类属性名称。我怎样才能在 python 2.x 中实现这一点?

这是在 Python 3.6 中运行良好的代码:

class IntField:
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise ValueError('expecting integer')
        instance.__dict__[self.name] = value

    def __set_name__(self, owner, name):
        self.name = name

class Example:
    a = IntField()
Run Code Online (Sandbox Code Playgroud)

python python-2.7

6
推荐指数
1
解决办法
1532
查看次数

标签 统计

python ×2

class ×1

python-2.7 ×1

python-3.x ×1