How to achieve inheritance using classmethod factory functions












0














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.










share|improve this question






















  • 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
















0














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.










share|improve this question






















  • 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














0












0








0







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.










share|improve this question













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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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


















  • 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












1 Answer
1






active

oldest

votes


















1














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.






share|improve this answer























  • 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 like super(B, cls).from_jdata(data) works
    – Dave
    Nov 15 at 23:13











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
});


}
});














draft saved

draft discarded


















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









1














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.






share|improve this answer























  • 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 like super(B, cls).from_jdata(data) works
    – Dave
    Nov 15 at 23:13
















1














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.






share|improve this answer























  • 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 like super(B, cls).from_jdata(data) works
    – Dave
    Nov 15 at 23:13














1












1








1






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.






share|improve this answer














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.







share|improve this answer














share|improve this answer



share|improve this answer








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 like super(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








  • 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 like super(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


















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

Can I use Tabulator js library in my java Spring + Thymeleaf project?