Re: Is Lexical Binding The Norm Yet?

Liste des GroupesRevenir à cl python 
Sujet : Re: Is Lexical Binding The Norm Yet?
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 21. Jan 2024, 08:28:12
Autres entêtes
Organisation : Stefan Ram
Message-ID : <prototypes-20240121082408@ram.dialup.fu-berlin.de>
References : 1 2 3 4 5 6 7 8 9 10 11
Newsgroups: comp.lang.python

ram@zedat.fu-berlin.de (Stefan Ram) writes:
from types import *

  What do you mean, the cloning part is missing?

import types

# create a new object
def counter_object(): pass

# attach a numeric field to the object
counter_object.counter_value = 0

# define a named function
def increment_value( self ): self.counter_value += 1

# attach the named function to the object as a method
counter_object.increment_value = \
types.MethodType( increment_value, counter_object )

# call the method
counter_object.increment_value()

# attach an unnamed function to the object
counter_object.get_value = \
types.MethodType( lambda self: self.counter_value, counter_object )

# call that method
# Prints "1".
print( counter_object.get_value() )

# An ad-hoc function to clone an object for the purpose of "prototype
# inheritance". Might need to be refined for more general uses.
def clone_object( object_ ):
    def new_object(): pass
    for attribute in dir( object_ ):
        if attribute[ :2 ]!= '__':
            if type( getattr( object_, attribute ))== types.MethodType:
                method = getattr( object_, attribute )
                function = types.FunctionType( method.__code__, {} )
                method = types.MethodType( function, new_object )
                setattr( new_object, attribute, method )
            else:
                field = getattr( object_, attribute )
                setattr( new_object, attribute, field )
    return new_object

# create two "clones" ("clone objects")
clone = clone_object( counter_object )
other = clone_object( counter_object )

# The clones "inherited" the counter field including its value.
# Prints "1 1 1".
print( counter_object.get_value(), clone.get_value(), other.get_value() )

# Each object's counter has a value independent from the other object's
# counter.
other.increment_value()

# Prints "1 1 2"
print( counter_object.get_value(), clone.get_value(), other.get_value() )


Date Sujet#  Auteur
20 Jan 24 * Re: Is Lexical Binding The Norm Yet?3Stefan Ram
21 Jan 24 `* Re: Is Lexical Binding The Norm Yet?2Stefan Ram
21 Jan 24  `- Re: Is Lexical Binding The Norm Yet?1Stefan Ram

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal