我们假设我有两个类:
#!/usr/bin/env python
class First():
glob = 'Global data'
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
print (arg1, arg2)
class Second(First):
def __init__(self):
print (self.glob)
他们从脚本调用:
#!/usr/bin/env python
import classes
data1 = 'First data part'
data2 = 'Second data part'
inst1 = classes.First(data1, data2)
inst2 = classes.Second()
这很有效,好的:
$ ./script.py
('First data part', 'Second data part')
Global data
我想在arg1
类中将arg2
和First
设为“全局”,然后在Second
中使用它:
class Second(First):
def __init__(self):
print (self.glob, self.arg1, self.arg2)
我如何实现它?
答案 0 :(得分:1)
class First(object):
glob = 'Global data'
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
#print (arg1, arg2)
class Second(First):
def __init__(self, *args):
super(Second, self).__init__(*args)
print (self.glob, self.arg1, self.arg2)
data1 = 'First data part'
data2 = 'Second data part'
inst1 = First(data1, data2)
inst2 = Second(data1, data2)
答案 1 :(得分:1)
First的 init 被第二个重载,从你的第二个类调用你的父类
class Second(First):
def __init__(self):
super(Second, self).__init__("argument1", "argument2")
print (self.glob, self.arg1, self.arg2)
在python3中它是这样的:
class Second(First):
def __init__(self):
super().__init__("argument1", "argument2")
print (self.glob, self.arg1, self.arg2)
答案 2 :(得分:1)
您可以在First
班级__init__()
方法中使用unpacking:
class First:
def __init__(self, *args):
for data in args:
print(data)
# in your child class, you need to call First.__init__(), via super()
class Second(First):
def __init__(self, *args):
super(Second, self).__init__(*args) # pass args to First.__init__()
用法:
import classes
i = Second("data", "data1", "data2", "data3")
使用解包允许您的类接受任意数量的参数,并使编写子类更快更容易。根据您的使用情况,有时最好使用字典解包,特别是如果您想要命名参数:
class First:
def __init__(self, **kwargs): # note the double wildcards here
print(kwargs.get('data1'))
print(kwargs.get('data2'))
class Second(First):
def __init__(self, **kwargs):
super(Second, self).__init__(**kwargs)
# usage
i = Second(data1="something", data2="something else", another_arg="Yahoo")