Passing a variable to a method in a class

I'm new to using classes and I'm trying to pass a variable to one of the methods inside of my class. How do I do it?

Here's an example of what I'm trying to accomplish:

class a_class():
     def a_method(txt):
          print txt

instance = a_class()
instance.a_method('hello world!)

P.S. I don't understand the whole self and __blah__ concepts yet, and I will avoid them at this point if I don't have to use them.

Answers


When writing an instance method for a class in Python- which looks exactly like what you've just coded up- you can't avoid using self. The first parameter to an instance method in Python is always the object the method is being called on. self is not a reserved word in Python- just the traditional name for that first parameter.

To quote from the official Python tutorial, chapter 9:

[...] the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.

Therefore, you need to define two parameters for your method. The first is always self- at least that is the conventional name- and the second is your actual parameter. So your code snippet should be:

class a_class(object):
    def a_method(self, txt):
        print txt

instance = a_class()
instance.a_method('hello world!')

Note that the class explicitly inherits from object (I'm not sure empty parentheses there are legal). You can also provide no inheritance, which is identical for most purposes, but different in some details of the behavior of the type system; the inheritance from object defines a_class as a new-style class rather than an old-style class, which is irrelevant for most purposes but probably worth being aware of.


Need Your Help

python long number data loss

python python-3.x biginteger data-loss

i am just starting with python (python3) because i read its good for the euler project since it can handle very big numbers.

Problems with git reset --hard after adding .gitattribute — local changes that should not be there

windows git gitattributes

I have observed CRLF problems after merging bundles from my colleague. Sometimes lines with LF were mixed into the sources, probably the ones that were merged into. Therefore, we have decided to ad...

Move all odd positioned element to left half and even positioned to right half in-place

performance algorithm data-structures time-complexity in-place

Given an array with positive and negative integers, move all the odd indexed elements to the left and even indexed elements to the right.