› Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 6: Python › MITx 6.100L Introduction to CS and Programming Using Python › Difference between functions and the ones defined under a class
- This topic is empty.
-
AuthorPosts
-
August 7, 2025 at 10:48 am #5219
Difference between functions and the ones defined under a class
byu/DigitalSplendid inlearnpythonComment
byu/DigitalSplendid from discussion
inlearnpythonComment
byu/DigitalSplendid from discussion
inlearnpythonComment
byu/DigitalSplendid from discussion
inlearnpythonYou’re absolutely right in your observation — and this is a very insightful question. Let’s break it down clearly:
✅ 1. Yes, str and other dunder methods are already defined by Python’s object system
When you create a class in Python, like:
class Node:
…your class automatically inherits from the base object class, unless you specify otherwise. And this base object class already defines a default version of many special (or “dunder”) methods like:
init (initialization),
str (string representation),
repr (developer-friendly representation),
eq (equality),
lt, gt, etc. (comparisons),
len, getitem, iter, etc.
For example, the default behavior of str is:
class A:
… pass
…
a = A()
print(a)
<main.A object at 0x7f9b1c2d2b50>This is not very helpful unless we override it.
✅ 2. When you define def str(self):, you are overriding the default behavior
You’re not creating something from scratch in the way you would with a regular function. Instead, you’re customizing (overriding) behavior that’s already defined at a higher level (inside Python’s built-in object class).
So yes, you’re right: using def str(self): looks like you’re defining a new function, but you’re actually:
🛠️ Overriding an existing system-defined method with custom logic tailored to your class.
✅ 3. Why still use def then?
Because Python is consistent in its syntax: all functions, whether you’re defining your own (def greet():) or overriding existing ones (def str(self):), are defined using def.
So:
def str(self):
return “Some readable output”is syntactically just a function definition — but semantically it’s a method override.
✅ 4. How does Python know what to do with str?
Internally, when you write:
print(some_object)
Python does something like this:
some_object.str()
If str() has been defined in your class, Python uses that. If not, it falls back to the default in the base object class — which is what gives you that <main.ClassName object at 0x12345678> output.
✅ 5. Summary
You’re absolutely correct: str, init, and similar dunder methods are predefined by Python.
You override them to customize behavior specific to your class.
The def keyword is still used for consistency in defining all methods, whether new or overridden.
Your class inherits these dunder methods from the object class, unless you override them.
-
AuthorPosts
- You must be logged in to reply to this topic.