Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class passing it self

Tags:

java

oop

class

I have a class that creates the object of type Smo. The object then calls a static method from another class. The static method requires that I pass the object to it that is calling it. How do I designate the calling object as the parameter to pass.

For example:

class Smo {    
    Smo() {
    }

    void sponge() {
        car.dancing(??????);    //////< ----------- how do I refer to self?
    }

    void dance() {
        //// do a little dance
    }
}

class Car() { 
    Car() {
    }

    dancing(Smo smo) {    
        smo.dance();
    }    
}
like image 532
James Andino Avatar asked Jun 28 '10 21:06

James Andino


People also ask

What does self mean in a class?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

What is Self in class method?

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

Why do you pass self in Python?

Need for Self in Python Unlike other programming languages, Python does not use the “@” syntax to access the instance attributes. This is the sole reason why you need to use the self variable in Python. The language contains methods that allow the instance to be passed automatically but not received automatically.

Do I need self for class methods?

Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.


1 Answers

Use the this keyword.

car.dancing(this);
like image 200
Mark Peters Avatar answered Oct 26 '22 07:10

Mark Peters