How to achieve inheritance using classmethod factory functions
How do I use/reuse implementations in the parent class when using the classmethod
approach for implementing factory functions?
In the example below, class A
is fine, but class B
is broken.
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = A.from_jdata(B, data)
res.__dict__['extra']='set'
return res
The context is that I'm trying to instantiate instances based on JSON configuration data. The inheritance hierarchy is deeper than just two classes, i.e. there are a number of children of class B
. The root of the inheritance hierarchy does some useful stuff in the factory function. Children classes should re-use that but add on some additional operations.
python inheritance factory-pattern
add a comment |
How do I use/reuse implementations in the parent class when using the classmethod
approach for implementing factory functions?
In the example below, class A
is fine, but class B
is broken.
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = A.from_jdata(B, data)
res.__dict__['extra']='set'
return res
The context is that I'm trying to instantiate instances based on JSON configuration data. The inheritance hierarchy is deeper than just two classes, i.e. there are a number of children of class B
. The root of the inheritance hierarchy does some useful stuff in the factory function. Children classes should re-use that but add on some additional operations.
python inheritance factory-pattern
I've done this in the past through registration of children and making the parent discriminate between children for deserialization.
– erip
Nov 15 at 22:51
add a comment |
How do I use/reuse implementations in the parent class when using the classmethod
approach for implementing factory functions?
In the example below, class A
is fine, but class B
is broken.
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = A.from_jdata(B, data)
res.__dict__['extra']='set'
return res
The context is that I'm trying to instantiate instances based on JSON configuration data. The inheritance hierarchy is deeper than just two classes, i.e. there are a number of children of class B
. The root of the inheritance hierarchy does some useful stuff in the factory function. Children classes should re-use that but add on some additional operations.
python inheritance factory-pattern
How do I use/reuse implementations in the parent class when using the classmethod
approach for implementing factory functions?
In the example below, class A
is fine, but class B
is broken.
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = A.from_jdata(B, data)
res.__dict__['extra']='set'
return res
The context is that I'm trying to instantiate instances based on JSON configuration data. The inheritance hierarchy is deeper than just two classes, i.e. there are a number of children of class B
. The root of the inheritance hierarchy does some useful stuff in the factory function. Children classes should re-use that but add on some additional operations.
python inheritance factory-pattern
python inheritance factory-pattern
asked Nov 15 at 22:49
Dave
3,66342249
3,66342249
I've done this in the past through registration of children and making the parent discriminate between children for deserialization.
– erip
Nov 15 at 22:51
add a comment |
I've done this in the past through registration of children and making the parent discriminate between children for deserialization.
– erip
Nov 15 at 22:51
I've done this in the past through registration of children and making the parent discriminate between children for deserialization.
– erip
Nov 15 at 22:51
I've done this in the past through registration of children and making the parent discriminate between children for deserialization.
– erip
Nov 15 at 22:51
add a comment |
1 Answer
1
active
oldest
votes
Use super
, of course:
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = super().from_jdata(data)
# res = super(B, cls).from_jdata(data) # in python 2
res.__dict__['extra']='set'
return res
In action:
In [6]: b = B.from_jdata({'_id':42, 'foo':'bar'})
In [7]: vars(b)
Out[7]: {'foo': 'bar', 'uuid': 42, 'extra': 'set'}
Note, what you were trying to do won't work because @classmethod
creates a descriptor that binds the class when called from either the class or the instance. You would have to access the raw function using something like:
res = A.__dict__['from_jdata'].__func__(B, data)
To make it work, but just use super
, that's what it is for.
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
1
@Dave I edited in to a comment:# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
it looks likesuper(B, cls).from_jdata(data)
works
– Dave
Nov 15 at 23:13
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328966%2fhow-to-achieve-inheritance-using-classmethod-factory-functions%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use super
, of course:
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = super().from_jdata(data)
# res = super(B, cls).from_jdata(data) # in python 2
res.__dict__['extra']='set'
return res
In action:
In [6]: b = B.from_jdata({'_id':42, 'foo':'bar'})
In [7]: vars(b)
Out[7]: {'foo': 'bar', 'uuid': 42, 'extra': 'set'}
Note, what you were trying to do won't work because @classmethod
creates a descriptor that binds the class when called from either the class or the instance. You would have to access the raw function using something like:
res = A.__dict__['from_jdata'].__func__(B, data)
To make it work, but just use super
, that's what it is for.
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
1
@Dave I edited in to a comment:# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
it looks likesuper(B, cls).from_jdata(data)
works
– Dave
Nov 15 at 23:13
add a comment |
Use super
, of course:
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = super().from_jdata(data)
# res = super(B, cls).from_jdata(data) # in python 2
res.__dict__['extra']='set'
return res
In action:
In [6]: b = B.from_jdata({'_id':42, 'foo':'bar'})
In [7]: vars(b)
Out[7]: {'foo': 'bar', 'uuid': 42, 'extra': 'set'}
Note, what you were trying to do won't work because @classmethod
creates a descriptor that binds the class when called from either the class or the instance. You would have to access the raw function using something like:
res = A.__dict__['from_jdata'].__func__(B, data)
To make it work, but just use super
, that's what it is for.
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
1
@Dave I edited in to a comment:# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
it looks likesuper(B, cls).from_jdata(data)
works
– Dave
Nov 15 at 23:13
add a comment |
Use super
, of course:
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = super().from_jdata(data)
# res = super(B, cls).from_jdata(data) # in python 2
res.__dict__['extra']='set'
return res
In action:
In [6]: b = B.from_jdata({'_id':42, 'foo':'bar'})
In [7]: vars(b)
Out[7]: {'foo': 'bar', 'uuid': 42, 'extra': 'set'}
Note, what you were trying to do won't work because @classmethod
creates a descriptor that binds the class when called from either the class or the instance. You would have to access the raw function using something like:
res = A.__dict__['from_jdata'].__func__(B, data)
To make it work, but just use super
, that's what it is for.
Use super
, of course:
class A(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@classmethod
def from_jdata(cls, data):
if '_id' in data:
data['uuid'] = data['_id']
del data['_id']
return cls(**data)
class B(A):
def __init__(self, **kwds):
super(B, self).__init__(**kwds)
@classmethod
def from_jdata(cls, data):
# goal: make an instance of B,
# using the logic that is implemented in A.from_jdata
# But does some extra stuff, akin to:
res = super().from_jdata(data)
# res = super(B, cls).from_jdata(data) # in python 2
res.__dict__['extra']='set'
return res
In action:
In [6]: b = B.from_jdata({'_id':42, 'foo':'bar'})
In [7]: vars(b)
Out[7]: {'foo': 'bar', 'uuid': 42, 'extra': 'set'}
Note, what you were trying to do won't work because @classmethod
creates a descriptor that binds the class when called from either the class or the instance. You would have to access the raw function using something like:
res = A.__dict__['from_jdata'].__func__(B, data)
To make it work, but just use super
, that's what it is for.
edited Nov 15 at 23:19
answered Nov 15 at 23:03
juanpa.arrivillaga
37k33470
37k33470
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
1
@Dave I edited in to a comment:# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
it looks likesuper(B, cls).from_jdata(data)
works
– Dave
Nov 15 at 23:13
add a comment |
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
1
@Dave I edited in to a comment:# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
it looks likesuper(B, cls).from_jdata(data)
works
– Dave
Nov 15 at 23:13
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
How to in python2.7 where arguments are required?
– Dave
Nov 15 at 23:10
1
1
@Dave I edited in to a comment:
# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
@Dave I edited in to a comment:
# res = super(B, cls).from_jdata(data) # in python 2
– juanpa.arrivillaga
Nov 15 at 23:13
it looks like
super(B, cls).from_jdata(data)
works– Dave
Nov 15 at 23:13
it looks like
super(B, cls).from_jdata(data)
works– Dave
Nov 15 at 23:13
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53328966%2fhow-to-achieve-inheritance-using-classmethod-factory-functions%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I've done this in the past through registration of children and making the parent discriminate between children for deserialization.
– erip
Nov 15 at 22:51