Chris
Chris

Reputation: 703

Initiating a method in a class

I'm new to both Django and Python.. I just started using them a few days ago and I can't quite figure out how to call a method other than the __init__ method for a class.

Here is the code for user.py

class User:
    def __init__(self, number):
        self.num = number

class Create:
    def __init__(self, something):
        self.test = something[1]

    def other(self, one):
        self.two = one

I can get __init__ to work by calling..

list = [3, 4, 5]
y = Create(list)
arrayelem = y.test

But I can't quite figure out how to call a method inside of the class Create. I've tried various methods and always end up with errors. Can somehow show me some syntactically correct methods of calling the method "other".

Note: I know the spacing is weird.. I can't get the spacing to work properly on stackoverflow for whatever reason..

Upvotes: 1

Views: 129

Answers (1)

Sam Starling
Sam Starling

Reputation: 5378

Good news - it's a simple one! To call other() on create, you'd do this:

list = [3, 4, 5]
y = Create(list)
y.other('one')

You just need to pass the parameters inside the parentheses, after the name of the method.

EDIT: I've just noticed you want to call other from inside the Create class. That'd look like this:

class Create:
    def __init__(self, something):
        self.test = something[1]
        self.other(123)

    def other(self, one):
        self.two = one

It's also worth bearing in mind that self.two won't exist when you get to the other() method.

Upvotes: 2

Related Questions