Difference between 'function' and 'method'

甜瓜 littlesweetmelon at gmail.com
Tue Mar 4 03:22:16 EST 2008


Howdy everyone,

     This is a big problem puzzles me for a long time. The core question is:
How to dynamically create methods on a class or an instance?

Let me state it step by step.
1.
def gunc(self):
    pass
class A(object):
    def func(self):
        pass
a = A()
a.func   # gives "bound method", type is "instancemethod"
A.func  # gives "unbound method", type is "instancemethod"
gunc    # gives "function", type if "function"

# ?? Does this line attach a method to instance?  ... I don't think so.
a.gunc = gunc

I found stardard library 'new' may help. Is that right?

2.
a = A()  # instance of old class A
# Do attach a new method to class A...
b = A()  # instance of new class A
Does "a" can get the new method automatically?
Does new method have the *same* concept level with old methods?
Especially, if there
are classes inherit from class A, how does name resolution work on this case?

3.
How do I write a decroator for a method? Eg:
class A(object):
    @my_dec
    def func(self):
        pass
Here, my_dec should return a method rathar than a function/lambda. Am I right?
What does @property  @staticmethod... really do? I cannot step-into them for
source code.

4.
If most of above questions can be solved, then it would be easy to implement
the feature: "dynamic property attach".
Eg:
One class can read/store settings from/to some file based on
the file content.
# File: cfg.ini
x = 1
y = python
config = SettingClass('cfg.ini')  # dynamically build up properties x and y.
x = config.x  #  x will be set to 1   (str -> int convertion would be
done by 'property x')
y = config.y  #  y will be set to 'python'
config.x = 9   # 'x = 9' is written to cfg.ini.

How to implement
^_^ Maybe there are some library does the same thing. What is it? How
to implement ?


Thank you for your attention!

---
ShenLei



More information about the Python-list mailing list