Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding methods to a Python class #17

Open
AlexTereshenkov opened this issue Feb 17, 2021 · 0 comments
Open

Adding methods to a Python class #17

AlexTereshenkov opened this issue Feb 17, 2021 · 0 comments

Comments

@AlexTereshenkov
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant