Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python calling method without 'self'

Tags:

python

class

self

So I just started programming in python and I don't understand the whole reasoning behind 'self'. I understand that it is used almost like a global variable, so that data can be passed between different methods in the class. I don't understand why you need to use it when your calling another method in the same class. If I am already in that class, why do I have to tell it??

example, if I have: Why do I need self.thing()?

class bla:     def hello(self):         self.thing()      def thing(self):         print "hello" 
like image 966
Synaps3 Avatar asked Sep 08 '13 02:09

Synaps3


People also ask

How do you call a function without self in Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

Can we create a function without self in Python?

The short answer is "because you can def thing(args) as a global function, or as a method of another class.

Do all methods in Python need self?

self is the first method of every Python class Some programming languages use the word this to represent that instance, but in Python we use the word self . When you define a class in Python, every method that you define, must accept that instance as its first argument (called self by convention).

What happens if you don't use self in Python?

If there was no self argument, the same class couldn't hold the information for both these objects. However, since the class is just a blueprint, self allows access to the attributes and methods of each object in python. This allows each object to have its own attributes and methods.


1 Answers

Also you can make methods in class static so no need for self. However, use this if you really need that.

Yours:

class bla:     def hello(self):         self.thing()      def thing(self):         print "hello" 

static edition:

class bla:     @staticmethod     def hello():         bla.thing()      @staticmethod     def thing():         print "hello" 
like image 93
Developer Avatar answered Sep 29 '22 17:09

Developer