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();
}
}
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.
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.
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.
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.
Use the this
keyword.
car.dancing(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With