Ask Your Question
1

Proper inheritance method for initializing specific instance of parent class

asked 2023-04-05 01:44:02 +0100

stillconfused gravatar image

updated 2023-04-05 01:44:24 +0100

I want to create a class that is a type of graph, together with some additional information. As a simple example, let's say we want to create a class MyCayleyGraph that, when initialized on a group and a set of generators, returns the Cayley DiGraph, but also has attributes storing the group and the generators used to make that Cayley graph. I've found a way of doing this, but I fear it's not the best, and I'd like to know if there is a preferred way.

My attempt:

class MyCayleyGraph():
     def __init__(self, group, gens):
        self._graph = group.cayley_graph(generators = gens)
        self._group = group
        self._gens = gens
    def __getattr__(self, attr):
        return getattr(self._graph, attr)
    def group(self):
        return self._group
    def gens(self):
        return self._gens

What I'm concerned about:

Ideally, I think this should be done by inheriting from the graph class, but I couldn't figure out how to make MyCayleyGraph inherit from DiGraph, and make the initialized graph actually be the Cayley graph of group and gens, rather than just an empty graph. What bothers me about the solution above is that I seem to be "sneakily" making a DiGraph object, because I can call DiGraph attributes on the resulting Cayley Graph, but the resulting object isn't actually of type DiGraph.

What's the correct way to do this?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-05 11:01:49 +0100

rburing gravatar image

Here is a way:

from sage.graphs.digraph import DiGraph
class MyCayleyGraph(DiGraph):
    def __init__(self, *args, **kwargs):
        group = kwargs.get('group', None)
        gens = kwargs.get('gens', None)
        if group and gens:
            self._group = group
            self._gens = gens
            super().__init__(group.cayley_graph(generators = gens))
        else:
            super().__init__(*args, **kwargs)
    def group(self):
        return self._group
    def gens(self):
        return self._gens

Example:

sage: G = DihedralGroup(5)
sage: CG = MyCayleyGraph(group=G, gens=[G.gen(0), G.gen(1)])
sage: CG.group()
Dihedral group of order 10 as a permutation group
sage: CG.gens()
[(1,2,3,4,5), (1,5)(2,4)]
sage: CG.vertices(sort=False)
[(),
 (1,5,4,3,2),
 (1,4,2,5,3),
 (1,3,5,2,4),
 (1,2,3,4,5),
 (2,5)(3,4),
 (1,5)(2,4),
 (1,4)(2,3),
 (1,3)(4,5),
 (1,2)(3,5)]

I did the constructor that way to keep CG.show() working; maybe there's a better way.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-04-05 01:44:02 +0100

Seen: 266 times

Last updated: Apr 05 '23