我是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 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)