Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Encapsulation in Python
Next article icon

In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role inPython’s object-oriented structure.

Example:

Python
classCar:def__init__(self,brand,model):self.brand=brand# Set instance attributeself.model=model# Set instance attributedefdisplay(self):returnself.brand,self.model# Create an instance of Carcar1=Car("Toyota","Corolla")# Call the display_info methodprint(car1.display())# Output: This car is a Toyota Corolla

Output
('Toyota', 'Corolla')

Explanation:

  • self in __init__:Used to assign values (brand and model) to the specific instance (car1).
  • self in display_info: Refers to the same car1 instance to access its attributes (brand and model).
  • Python automatically passes car1 as the first argument to display.

Let's understand the use of self as default argument in python in detail:

Why Python Uses 'Self' As Default Argument?

The main reason Python uses self as the default argument is to makeobject-oriented programming explicit rather than implicit. By requiring the instance of the class to be passed explicitly as the first parameter to every instance method, Python ensures that the code is clear and unambiguous. This explicit approach makes it immediately obvious that methods are operating on an instance of the class, which enhances code readability and avoids confusion, especially in complex inheritance scenarios.

Why Not Implicit?

Unlike some other programming languages, Python requires self explicitly because:

  • Clarity: Explicit is better than implicit (Python’s philosophy).
  • Flexibility: You can name it anything, but self is a convention.
  • Consistency: All instance methods in Python use this approach, making it uniform.

Below, are the example of using 'Self' As A Default Argument inPython.

Example 1: Object Initialization & Method Invocation

Python
classgfg:def__init__(self,topic):self._topic=topic# Rename the instance variable to avoid conflictdeftopic(self):print("Topic:",self._topic)# Access the renamed variable# Creating an instance of gfgins=gfg("Python")# Calling the topic methodins.topic()

Output
Topic: Python

Explanation: In this example, 'self' is used to refer to the instance of the class, 'ins.' Without the explicit use of 'self,' it would be unclear which instance the method is referring to and the code might become ambiguous.

Example 2: Circle Class for Area Calculation Example

In this example, 'self' is crucial for accessing the'r' attribute of the specific instance 'ins.' The use of'self' ensures that the method operates on the attributes of the correct instance.

Python
classCircle:def__init__(self,r):self.r=rdefarea(self):a=3.14*self.r**2returna# Creating an instance of Circleins=Circle(5)# Calling the area methodprint("Area of the circle:",ins.area())

Output
Area of the circle: 78.5
Suggested Quiz
6 Questions

What is the purpose of the self keyword in Python classes?

  • A

    It refers to the class itself

  • B

    It is used to define private methods

  • C

    It refers to the current instance of the class

  • D

    It refers to the superclass

Explanation:

self represents the instance of the class. It's used to access instance variables and methods from within the class.

What will be the output of the following code?

class MyClass:

def __init__(self, value):

self.value = value

def get(self):

return self.value

obj = MyClass(10)

print(obj.get())

  • A

    None

  • B

    Value

  • C

    10

  • D

    Error

Explanation:

The constructor initializes self.value with 10, and get() returns that value.

Why must self be the first parameter in instance methods?

  • A

    It's required by the Python interpreter to distinguish instance methods

  • B

    It's used for memory management

  • C

    It's a syntax convention, not a requirement

  • D

    It's only needed when inheriting from another class

Explanation:

The Python interpreter automatically passes the instance (self) as the first argument when calling instance methods.

What will happen if self is omitted from an instance method definition?

class Test:

def show():

print("Hello")

t = Test()

t.show()


  • A

    Prints Hello

  • B

    Raises TypeError

  • C

    Prints nothing


  • D

    Prints None

Explanation:

The method show() doesn't accept self, so when the instance t is used to call it, Python still passes self, causing a TypeError.

What will be the output of the following code?

class Sample:

def __init__(this, x):

this.x = x

def show(this):

print(this.x)

s = Sample(5)

s.show()

  • A

    this

  • B

    5

  • C

    Error

  • D

    None

Explanation:

Although this is used instead of self, it's just a parameter name. The code works and prints 5.

What does self.__class__ refer to in an instance method?
  • A

    The class of the self instance

  • B

    The parent class

  • C

    The method name

  • D

    The memory location of self

Explanation:

self.__class__ refers to the class to which the instance belongs, useful for introspection or logging.

Quiz Completed Successfully
Your Score :   2/6
Accuracy :  0%
Login to View Explanation
1/61/6< Previous Next >

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp