简体   繁体   中英

object type error in class method in python

I have a code-

from statistics import mean
from random import choice
from random import sample

import networkx as nx


class MyGraph(nx.Graph):
    def __init__(self, num_nodes, target_deg, target_wght, max_wght=5):
        super().__init__()
        self.num_nodes = num_nodes
        self.target_deg = target_deg
        self.target_wght = target_wght
        self.max_wght = max_wght
        self.add_nodes_from(range(self.num_nodes))
        while self.avg_deg() < self.target_deg:
            n1, n2 = sample(self.nodes(), 2)
            self.add_edge(n1, n2, weight=1)
        while self.avg_wght() < self.target_wght:
            n1, n2 = choice(list(self.edges()))
            if self[n1][n2]['weight'] < self.max_wght:
                self[n1][n2]['weight'] += 1

    def avg_deg(self):
        return self.number_of_edges() * 2 / self.num_nodes

    def avg_wght(self):
        wghts = []
        for i in range(self.num_nodes):
            for j in range(i + 1, self.num_nodes):
                try:
                    wghts.append(self[i][j]['weight'])
                except KeyError:
                    pass
        return mean(wghts)




a=MyGraph(100,4,5)

print(type(a))      

output-

<class '__main__.MyGraph'>

I have defined the object as nx.graph then why is the object of MyGraph coming different from networkx type? In my class defintion I have mentioned the object to be nx.Graph so when I call the class it should return me a networkx type object.

With this code:

class MyGraph(nx.Graph):

You created the new class that is inherited from nx.Graph . It is a new class, not a nx.Graph so when you create the instance of this class, in its type the name of your new class is written. It is normal behavior not for only Python, but for nearly every language with OOP support.

Inherited classes can use all non-private methods of the parent classes:

Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments). This is occasionally useful to clients as well. (Note that this only works if the base class is accessible as BaseClassName in the global scope.)

The whole inheritance concept was created about it. I recommend you to read a Wikipedia article about inheritance to fully understand it because it is the core concept for most popular languages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM