Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

instantiating in a class - Python 3

–1 vote
asked Jan 5, 2021 by SHERI LINETTE Gunville (110 points)
How to use 'self' in python 3 online here, it works in pycharm, but it adds the (self) itself. It's not seeing attack as defined as it's inside the class. it's not transferring to the object somehow. It should just print 'ouch'.

I've also tried def__init__self(): but this online editor python 3 version doesn't seem to recognize the __init__self

class Enemy:
     def attack(self):
enemy1 = Enemy

Why no ouch???? :-)

1 Answer

+1 vote
answered Jan 7, 2021 by Peter Minarik (87,810 points)
edited Jan 8, 2021 by Peter Minarik

You need to add the argument list (empty in your case) after the class name to properly instantiate it. In many languages this step is referred as calling the constructor.

enemy1 = Enemy()

With this, your code works fine.

commented Nov 18, 2021 by edson (110 points)
Yup, below is an example:
num_nodes = 5
edges = [(0,1), (0,4), (1,2), (1,3), (1,4), (2,3), (3,4)]

#Defining a Graph class to maintain the info for the graph as an adjacency list
class Graph:
    def __init__(self, num_nodes, edges):
        self.num_nodes = num_nodes
        self.edges = edges

graph = Graph(num_nodes, edges)

This should print: "Test"
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.