Skip to content

Adding methods to a Python class #17

@AlexTereshenkov

Description

@AlexTereshenkov

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