Ruby's alais in PythonWell I was thinking about the use of the alias method in Ruby and wanted to know how to do something similar in Python. the problem is that Python don't allow for already defined classes to be reopened and added to. if you did this
class Person:
def __init__(self, name):
self.name = name
def print_name(self):
print self.name
class Person:
def good_name(self):
print "%s is a good name" % self.name
bob = Person("bob")
you would get an error that "this constructor takes no arguments" this is because the second class statement "class Person:" completely overwrites the old class with a new one. This annoyed me because in Ruby the second class statement would open the previous class statement and add to it.
but then I realized
every name attached to a Python object is an attribute(property) and is publicly modifiable. so you could do this:
class Person:
def __init__(self, name):
self.name = name
def print_name(self):
print self.name
def good_name(self):
print "%s is a good name" % self.name
Person.good_name = good_name
bob = Person("bob")
bod.good_name() #> "bob is a good name"
following this line of thinking I realized that
this is possible too
class Person:
def __init__(self, name):
self.name = name
def print_name(self):
print self.name
def good_name(self):
print "%s is a good name" % self.name
Person.good_name = good_name
Person.print_name_later = Person.print_name
def print_name(self):
self.print_name_later()
self.good_name()
Person.print_name = print_name
del good_name
del print_name
bob = Person("bob")
bod.print_name() #> "bob" /n "bob is a good name"
and there you have it I added to a pre-existing python method by first giving the Person class a new property and setting its value to the function object of the method I wanted to overwrite
then defining a new method where I call the old method renamed and call another method
and then setting the Person class property that holds a reference to the old function object to the new function object
the principle and effect tis the exact same as this use of Ruby's alias
EDIT: i just realized that it would be a good idea to add these lines
del good_name
del print_name
this ensures that the global names get removed just ensures that no conflicts arise