473,806 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

New inited instance of class?

Is there a builtin way of making making another instance of your own
class? I really expected type(self)(*arg s, **keywords) to work this way.
Currently i'm doing this:

def new(self,*args, **keywords):
from new import instance
s=instance(self .__class__)
if hasattr(D(),'__ init__'):
s.__init__(*arg s,**keywords)
return s

--
"You have to impress him! Be independent and plucky, but often do
things that are moronic and out of character!"
--50s Diana Dane to 90s Diana Dane
Jul 18 '05
18 2718
Peter Otten wrote:
Samuel Kleiner wrote:
So can I make all my classes derive from object without
doing so explicitly- IE, without having to change every
single top-level class definition?


You can do it on a per-file basis by putting

__metaclass__ = type

That's what I meant. Great, thanks.

--
"You've got to kill people,
and when you've killed enough they stop fighting." --Curtis LeMay
Jul 18 '05 #11
Peter Otten <__*******@web. de> wrote in message ...
Samuel Kleiner wrote:
So can I make all my classes derive from object without
doing so explicitly- IE, without having to change every
single top-level class definition?


You can do it on a per-file basis by putting

__metaclass_ _ = type

once before the class definitions.


That strikes me as a very *bad* idea, because it's no longer obvious that
the classes themselves are new-style, and the OP might develop a bad habit
of using this to avoid typing '(object)' all the time. (Or he might show us
all for fools, if ':' becomes shorthand for '(object):'.)

Aside from that, metaclasses are a more advanced and less-commonly-used
feature of classes, and therefore probably more vulnerable to change. I
know it should work, but am uneasy that it might manifest some unexpected
behavior (or bug).
--
Francis Avila

Jul 18 '05 #12
Fredrik Lundh wrote in message ...
Francis Avila wrote:
If you're curious, look in the Python Language Reference at the old and new style classes to see the differences. There's absolutely no advantage to
old style classes
except performance:

http://www.python.org/~jeremy/weblog/030506.html


That's not a big difference, and in any case:
http://www.python.org/doc/current/wh...00017200000000
00000000

Creation of new-style instances is faster. I seem to recall Alex Martelli
also thinking that new-style classes are faster all-around. In any case,
he's gung-ho on new-style classes, even more than I am.
it's vital for understanding the still poorly-documented new-style

classes.
documentatio n may also be seen as an advantage, of course.


True, but unless one is doing something elaborate (can't even think *what*)
or relies on the old mro, the only difference is that base classes will
derive from object. If there is code that depends upon the old mro, it
should probably be fixed anyway.

And it's probably not a problem. From "What's new in 2.3", section 16:
"""
The method resolution order used by new-style classes has changed, though
you'll only notice the difference if you have a really complicated
inheritance hierarchy. Classic classes are unaffected by this change. Python
2.2 originally used a topological sort of a class's ancestors, but 2.3 now
uses the C3 algorithm as described in the paper ``A Monotonic Superclass
Linearization for Dylan''. To understand the motivation for this change,
read Michele Simionato's article ``Python 2.3 Method Resolution Order'', or
read the thread on python-dev starting with the message at
http://mail.python.org/pipermail/pyt...er/029035.html.
Samuele Pedroni first pointed out the problem and also implemented the fix
by coding the C3 algorithm. """

So I still stand by the claim that one should stop using old-style classes.
Changing old-style to new-style classes is more problematic, but I don't see
that it's much more. If the code is old enough to use changed/depreciated
pre-2.2 features, changing classic classes to new-style is the least of your
problems. But if it's 2.2 code, the jump to 2.3 is small and nothing but an
advantage--only a policy decision should keep anyone in 2.2.

What are the serious compatibility problems with changing an old-style class
to a new-style class (which I haven't encountered)? My understanding is
that the headaches are from *mixing* classic and new-style classes in the
same hieararchy.
--
Francis Avila

Jul 18 '05 #13
Aahz wrote in message ...
In article <vt************ @corp.supernews .com>,
Francis Avila <fr***********@ yahoo.com> wrote:

If you're curious, look in the Python Language Reference at the old
and new style classes to see the differences. There's absolutely no
advantage to old style classes, so stop usin' 'em.
<raised eyebrow> In addition to the factors Fredrik mentioned,


I responded to those concerns separately.
there's
also the issue that new-style classes are more of a moving target WRT
syntax and semantics; for complex uses, it can be tricky (or impossible)
to get the same code working the same way on both 2.2 and 2.3.
True, but if you are coding for both 2.2 and 2.3, you have to avoid a great
deal more than new-style classes (but, what changed besides the mro?). If
we're worried about compatability with pre-2.2, shouldn't we not be using
__class__ either? Barring trying to get code running on 2.2, it seems we
should be coding for new-style classes where possible, and it's possible
almost everywhere. Classic classes are on their way out, and eight more
keystrokes now means fewer headaches later.
More than that, you *can't* use new-style classes for exceptions.
Exceptions should be derived from Exception or a subclass thereof, so
whether they're new- or old-style is not an issue. When Python supports
new-style class exceptions, Exception will be changed to reflect that.
So
please stop telling people to avoid classic classes.


Someone better tell Alex Martelli, too, because IIRC he is far more gung-ho
on using new-style classes absolutely everywhere than I am. I believe he
said the only time he uses them is when he forgets to type (object), which
is about where I'm at.
--
Francis Avila

Jul 18 '05 #14
Francis Avila wrote:
You can do it on a per-file basis by putting

__metaclass __ = type

once before the class definitions.
That strikes me as a very *bad* idea, because it's no longer obvious that
the classes themselves are new-style, and the OP might develop a bad habit
of using this to avoid typing '(object)' all the time. (Or he might show
us all for fools, if ':' becomes shorthand for '(object):'.)


I indeed expect the classic/new-style class schism to go away even before
3.0 and am looking forward to remove both (object) in class A(object): and
__metaclass__ = type, which I expect to be equally *not* hard :-)
Aside from that, metaclasses are a more advanced and less-commonly-used
feature of classes, and therefore probably more vulnerable to change. I
know it should work, but am uneasy that it might manifest some unexpected
behavior (or bug).


For the above recipe to work you need not know what metaclasses are. I'm not
in the ignorance is good camp, though. The more people play with
metaclasses (are there any in production yet?), the sooner the strengths
and weaknesses of this construct will reveal.

If you have the appropriate tests and can make your program pass them by
providing an explicit object superclass instead of the __metaclass__ line,
the fix should be a breeze.
Peter
Jul 18 '05 #15
In article <vt************ @corp.supernews .com>,
Francis Avila <fr***********@ yahoo.com> wrote:
Aahz wrote in message ...

So please stop telling people to avoid classic classes.


Someone better tell Alex Martelli, too, because IIRC he is far more
gung-ho on using new-style classes absolutely everywhere than I am. I
believe he said the only time he uses them is when he forgets to type
(object), which is about where I'm at.


There's a big difference between being gung-ho on new-style classes and
telling people to stop using old-style classes. There's also a big
difference between saying, "I never use classic classes," and, "You
should avoid classic classes." I'll admit that Alex posts enough that I
don't read everything he says, but I don't recall him going as far as you
do -- and I'd be rather shocked if he did because he almost always
appropriately qualifies his advice.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote
programs, then the first woodpecker that came along would destroy civilization.
Jul 18 '05 #16
aa**@pythoncraf t.com (Aahz) writes:
for complex uses, it can be tricky (or impossible) to get the same
code working the same way on both 2.2 and 2.3.


Specific example? (I guess you're talking about C3 here?)

Cheers,
mwh

--
[Perl] combines all the worst aspects of C and Lisp: a billion
different sublanguages in one monolithic executable. It combines
the power of C with the readability of PostScript. -- Jamie Zawinski
Jul 18 '05 #17
"Francis Avila" <fr***********@ yahoo.com> wrote in message news:<vt******* *****@corp.supe rnews.com>...> And it's probably not a problem. From "What's new in 2.3", section 16:
"""
The method resolution order used by new-style classes has changed, though
you'll only notice the difference if you have a really complicated
inheritance hierarchy.
The "What's new" is right in practice, nevertheless, just for the sake
of
giving a counter-example, here is a very simple hierarchy which is
forbidden in 2.3 and valid in 2.2:
class C(object,type): pass

....
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, type

So I still stand by the claim that one should stop using old-style classes.
I don't disagree but see next point.
What are the serious compatibility problems with changing an old-style class
to a new-style class (which I haven't encountered)? My understanding is
that the headaches are from *mixing* classic and new-style classes in the
same hieararchy.


Not really, in my experience the mixture works well enough. Right now,
I see two other problems: 1) exceptions MUST be old style (as Aahz
already
pointed out) and 2) the are subtle differences in the working of
special methods such as __setattr__ and __getattr__ (and I think
Aahz was alluding to this too).
For new style classes x.__setattr__(k ,v) is the same than
type(x).__setat tr__(x,k,v) but the lookup rule is different for old
style classes. See the Nutshell for more.
Michele
Jul 18 '05 #18
"Francis Avila" <fr***********@ yahoo.com> wrote in message news:<vt******* *****@corp.supe rnews.com>...
That strikes me as a very *bad* idea, because it's no longer obvious that
the classes themselves are new-style, and the OP might develop a bad habit
of using this to avoid typing '(object)' all the time. (Or he might show us
all for fools, if ':' becomes shorthand for '(object):'.)
I don't disagree.
Aside from that, metaclasses are a more advanced and less-commonly-used
feature of classes, and therefore probably more vulnerable to change. I
know it should work, but am uneasy that it might manifest some unexpected
behavior (or bug).


Maybe you are worrying a bit too much here, since the __metaclass__=t ype
idiom is quite safe in practice. Of course, it can give surprises,
such as the following:

__metaclass__=t ype

class E: pass

raise E() # not the error you would expect

Nevertheless, you should derive exceptions from Exception, so this
does not happen in real live. The other caution is with certain usages
of special methods, but they are relatively rare.

On the other hand, custom metaclasses different from type can
give more than one surprise, so I would not suggest their use to
the causal programmer. BTW, also the experienced programmer can
live without metaclasses for 99% of tasks. But they may come
handy in special situations.

Michele
Jul 18 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2373
by: Robert Ferrell | last post by:
I have a question about assigning __call__ to an instance to make that instance callable. I know there has been quite a bit of discussion about this, and I've read all I can find, but I'm still confused. I'd like to have a factory class that takes a string argument and returns the appropriate factory method based on that string. I'd like the instances to be callable. Like this: fact = Factory('SomeThing') aSomeThing = fact(some...
14
3343
by: Sridhar R | last post by:
Consider the code below, class Base(object): pass class Derived(object): def __new__(cls, *args, **kwds): # some_factory returns an instance of Base # and I have to derive from this instance!
6
7747
by: Andre Meyer | last post by:
Hi all I have been searching everywhere for this, but have not found a solution, yet. What I need is to create an object that is an instance of a class (NOT a class instance!) of which I only know the name as a string. This what I tried: class A:
4
3919
by: | last post by:
Hi I have a list containing several instance address, for example: I'd like to invoke a method on each of these instance but I don't know : 1. if its possible 2. how to proceed
18
6962
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
7
1683
by: Göran Tänzer | last post by:
Hi, i've written a class which does some calculations for my web application. These informatinos are different for each page request - the current user is not important. i have about 10 aspx pages and 20 ascx user controls. In most of these pages/user controls i need the informations of this class. First i created an instance of this class in every page/user control i
3
4237
by: Adam | last post by:
We have a web site that uses .vb for the web pages and .cs for a class module. We are getting the error in .NET 2.0 and VS 2005 beta 2. It does work with .NET 1.1. When trying to access a page that needs the class module I get an error on web site: Object reference not set to an instance of an object Here is where the error is:
12
3121
by: titan nyquist | last post by:
I have a class with data and methods that use it. Everything is contained perfectly THE PROBLEM: A separate thread has to call a method in the current instantiation of this class. There is only ever ONE instantiation of this class, and this outside method in a separate thread has to access it. How do i do this?
0
1465
by: Ravi gowda | last post by:
Hi, i am getting Error on status bar :Applet trustfield Extapp not inited and web page will stops when loging in to a web site Please suggest on this issue Regards, Ravi,
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10617
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10364
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5545
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4328
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.