Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Adding methods to a Python class #17

Copy link
Copy link
@AlexTereshenkov

Description

@AlexTereshenkov
Issue body actions

Hey! Thank you for the comparison document, very useful to read to compare and contrast. There is one comment that has drawn my attention. I wonder whether I have misunderstood what you meant in this sentence:

However, Ruby has one advantage: it can add methods to existing classes, while Python by default can't do this (although it's possible with the use of external libraries).

In Python, it is possible to add a method to a class that has already been declared, e.g. using a lambda:

class Foo:
    pass


Foo.bar = lambda self, x: x*2
f = Foo()
print(f.bar(3))
# 6

or using a function definition:

class Spam:
    pass


def bar(self, x):
    return x*2

Spam.bar = bar
f = Spam()
print(f.bar(3))

Unless I am mistaken, this functionality has been available since the early versions and is an integral part of the language semantics. Or have I misunderstood you?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.