🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: pl.comp.lang.python
Article #27125

Metaklasy w Pythonie

#27125
From: pr
Date: Sun, 03 Jan 2010 22:40
37 lines
2088 bytes
Witam,

Czy da się tak zrobić aby "metaklasa była lazy", to znaczy, aby
wywołanie metody __new__ w MyMeta nastąpiło w wyniku świadomego
odwołania do klasy B (patrz kod niżej), czyli, np kiedy zrobię tak:
print B.myattr
print B().myattr
a nie w chwili gdy interpreter napotka już tylko samą definicję klasy
(czyli za każdym razem, niezależnie czy jej używam):
class B(A): pass
?

Z góry dzięki za odpoweidź.

class MyMeta(type):

    def __new__(cls, name, bases, attrs):
        print "Metaclass"
        super_new = super(MyMetal, cls).__new__
        parents = [b for b in bases if isinstance(b, MyMeta)]
        if not parents:
            return super_new(cls, name, bases, attrs)

        module = attrs.pop('__module__')
        new_class = super_new(cls, name, bases, {'__module__':
module})
        ...
        ...
        return new_class


class A(object):

    __metaclass__ = MyMeta

class B(A):
    pass
Technical Details
Message-ID: <acd8187e-60ea-4eda-9eb6-52f5d3754d2b@a21g2000yqc.googlegroups.com>
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!news.gazeta.pl!newsfeed.pionier.net.pl!news.glorb.com!postnews.google.com!a21g2000yqc.googlegroups.com!not-for-mail

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!news.gazeta.pl!newsfeed.pionier.net.pl!news.glorb.com!postnews.google.com!a21g2000yqc.googlegroups.com!not-for-mail
From: pr <cricogik@gmail.com>
Newsgroups: pl.comp.lang.python
Subject: Metaklasy w Pythonie
Date: Sun, 3 Jan 2010 14:40:22 -0800 (PST)
Organization: http://groups.google.com
Lines: 38
Message-ID: <acd8187e-60ea-4eda-9eb6-52f5d3754d2b@a21g2000yqc.googlegroups.com>
NNTP-Posting-Host: 81.186.224.2
Mime-Version: 1.0
X-Trace: posting.google.com 1262558422 4052 127.0.0.1 (3 Jan 2010 22:40:22 GMT)
X-Complaints-To: groups-abuse@google.com
NNTP-Posting-Date: Sun, 3 Jan 2010 22:40:22 +0000 (UTC)
Complaints-To: groups-abuse@google.com
Injection-Info: a21g2000yqc.googlegroups.com; posting-host=81.186.224.2;  posting-account=0dYzQQoAAADD4mKBs1MFtArJhD70zsVy
User-Agent: G2/1.0
X-HTTP-UserAgent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1;  Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR  3.0.30729; Media Center PC 6.0; InfoPath.2),gzip(gfe),gzip(gfe)
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit