Google Gruplar, artık yeni Usenet gönderilerini veya aboneliklerini desteklememektedir. Geçmişteki içerikler görüntülenebilir kalmaya devam edecek.

How to Adding Functionality to a Class by metaclass(not by inherit)

1 görüntüleme
İlk okunmamış mesaja atla

Kyo Guan

okunmadı,
12 Ağu 2005 00:22:1712.08.2005
alıcı pytho...@python.org
How to Adding Functionality to a Class by metaclass(not by inherit)

#example:

import inspect

class Foo(object):
def f(self):
pass

def g(self):
pass

class MetaFoo(type):
def __init__(cls, name, bases, dic):
super(MetaFoo, cls).__init__(name, bases, dic)

for n, f in inspect.getmembers(Foo, inspect.ismethod):
setattr(cls, n, f)

#Bar want to achieve Foo's part/all functionality, but not by inherit

class Bar(object):
__metaclass__ = MetaFoo


>>> b = Bar()
>>> b.f()
TypeError: unbound method f() must be called with Foo instance as first argument (got nothing instead)
>>> Bar.f
<unbound method Foo.f>
>>> b.f
<unbound method Foo.f>

how can I set Bar.f as <unbound method Bar.f>


kyo guan

okunmadı,
12 Ağu 2005 00:25:3412.08.2005
alıcı pytho...@python.org

Steven Bethard

okunmadı,
12 Ağu 2005 00:55:1212.08.2005
alıcı
kyo guan wrote:
> How to Adding Functionality to a Class by metaclass(not by inherit)
>
[snip]

>
> class MetaFoo(type):
> def __init__(cls, name, bases, dic):
> super(MetaFoo, cls).__init__(name, bases, dic)
>
> for n, f in inspect.getmembers(Foo, inspect.ismethod):
> setattr(cls, n, f)
^^^^^^^^^
f.im_func

See if that works. I think it should.

But the real question is why you want to do this. Why can't you just
inherit from Foo?

STeVe

Paolino

okunmadı,
12 Ağu 2005 07:09:4512.08.2005
alıcı kyo guan, pytho...@python.org
Dont' know where are you going with that but if what you need is
cancelling some attributes when inheriting then probably this is a
cleaner approach:

class Meta(type):


def __init__(cls, name, bases, dic):

def attributeError(*_):
raise AttributeError
for base in bases:
for dont in base.privates:
setattr(cls,dont,attributeError) #override private methods

class Foo(object):
privates=('f',)


def f(self):
pass
def g(self):
pass

class Bar(Foo):
__metaclass__ = Meta

b=Bar()
b.g()
b.f()

and it implies writing only one metaclass.




___________________________________
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB
http://mail.yahoo.it

0 yeni ileti