如何从子 class 对象访问基 class 方法 *args?
How to access base class method *args from child class object?
我正在尝试从子 class 对象获取基础 class 方法 *args
。这是代码:
class BaseView():
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class SecondLevelClass(BaseView):
def print_kwargs(self):
for key, value in self.__dict__.items():
print(key, value)
for x in self.args:
print(x)
some_object = SecondLevelClass('something', name="John", second_name="Keller", age=23,
location='France')
print(vars(some_object))
print(type(some_object))
print(some_object.print_kwargs())
错误消息说:AttributeError: 'SecondLevelClass' object has no attribute 'args'
如果我想打印它们,如何获取传递给 __init__
的 *args
?
更新:
更新了缺少行的代码。
如果您在派生的 class 的 __init__()
方法中保存属性的副本,您就可以使用它,因此它的 print_kwargs()
方法可以访问它们。
我的意思是:
class BaseView():
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class SecondLevelClass(BaseView):
# ADDED
def __init__(self, *args, **kwargs):
self.args = args
super().__init__(*args, **kwargs)
def print_kwargs(self):
for key, value in self.__dict__.items():
print(key, value)
for x in self.args:
print(x)
some_object = SecondLevelClass('something', name="John", second_name="Keller", age=23,
location='France')
print(vars(some_object))
print(type(some_object))
print(some_object.print_kwargs())
我正在尝试从子 class 对象获取基础 class 方法 *args
。这是代码:
class BaseView():
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class SecondLevelClass(BaseView):
def print_kwargs(self):
for key, value in self.__dict__.items():
print(key, value)
for x in self.args:
print(x)
some_object = SecondLevelClass('something', name="John", second_name="Keller", age=23,
location='France')
print(vars(some_object))
print(type(some_object))
print(some_object.print_kwargs())
错误消息说:AttributeError: 'SecondLevelClass' object has no attribute 'args'
如果我想打印它们,如何获取传递给 __init__
的 *args
?
更新: 更新了缺少行的代码。
如果您在派生的 class 的 __init__()
方法中保存属性的副本,您就可以使用它,因此它的 print_kwargs()
方法可以访问它们。
我的意思是:
class BaseView():
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class SecondLevelClass(BaseView):
# ADDED
def __init__(self, *args, **kwargs):
self.args = args
super().__init__(*args, **kwargs)
def print_kwargs(self):
for key, value in self.__dict__.items():
print(key, value)
for x in self.args:
print(x)
some_object = SecondLevelClass('something', name="John", second_name="Keller", age=23,
location='France')
print(vars(some_object))
print(type(some_object))
print(some_object.print_kwargs())