473,396 Members | 2,038 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

New inited instance of class?

Is there a builtin way of making making another instance of your own
class? I really expected type(self)(*args, **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__(*args,**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 #1
18 2678
Samuel Kleiner <sa*@samuel-kleiners-computer.local> writes:
Is there a builtin way of making making another instance of your own
class? I really expected type(self)(*args, **keywords) to work this way.


Doesn't self.__class__(*args, **keywords) work?

|>oug
Jul 18 '05 #2

Samuel Kleiner wrote in message ...
Is there a builtin way of making making another instance of your own
class?
You mean, from the inside (from one of the instance methods of the class)?

def new(self, *args, **kargs):
return self.__class__(*args, **kargs)
I really expected type(self)(*args, **keywords) to work this way.
Works for me. What traceback does it give you?
Currently i'm doing this:

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


That's ugly.

--
Francis Avila
Jul 18 '05 #3
Francis Avila wrote:

Samuel Kleiner wrote in message ...
Is there a builtin way of making making another instance of your own
class?
You mean, from the inside (from one of the instance methods of the class)?


Yes.
def new(self, *args, **kargs):
return self.__class__(*args, **kargs)


This works. Thanks.
I really expected type(self)(*args, **keywords) to work this way.


Works for me. What traceback does it give you?


Not for me. I really want to call it as the function itself, and

type(self)(argument1,argument2,argument3)

fails with

Traceback (most recent call last):
File "<stdin>", line 139, in ?
File "<stdin>", line 78, in __add__
TypeError: instance() takes at most 2 arguments (3 given)

whereas

self.__class__(argument1,argument2,argument3)

does not
Currently i'm doing this:

[my code]

That's ugly.


Yes.

--
On an encouraging note, however, I found that throughout the source code,
extremely conservative coding practices and good error checking everywhere
means that our software does not crash when handling IPv6 addresses.
--Joe Loughry, Lockheed Martin Space and Strategic Missiles, RADIANT MERCURY
Jul 18 '05 #4
Samuel Kleiner wrote in message ...
Not for me. I really want to call it as the function itself, and

type(self)(argument1,argument2,argument3)

fails with

Traceback (most recent call last):
File "<stdin>", line 139, in ?
File "<stdin>", line 78, in __add__
TypeError: instance() takes at most 2 arguments (3 given)


Ah! You're using classic classes. Don't do that.

Observe:
class classic: pass
type(classic) <type 'classobj'> type(classic()) <type 'instance'> classic().__class__ <class __main__.classic at 0x00F58030>
class newstyle(object): pass
type(newstyle) <type 'type'> type(newstyle()) <class '__main__.newstyle'> newstyle().__class__ <class '__main__.newstyle'>


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.

There's a grand old intro (by Guido) to new-style classes at python.org,
linked from "What's New" in the 2.3 docs. I keep hunting for that link: it
really should be in the distributed docs, because it's vital for
understanding the still poorly-documented new-style classes.
--
Francis Avila

Jul 18 '05 #5
Francis Avila wrote:
Ah! You're using classic classes. Don't do that.


Ok, thanks-

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?

--
Loren ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh eusmod tincidunt ut laoreet dolore magna aliquam erat
volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
Jul 18 '05 #6
Samuel Kleiner wrote in message ...
Francis Avila wrote:
Ah! You're using classic classes. Don't do that.


Ok, thanks-

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?


I doubt it. But I think sed or re could take care of that quite easily with
a search/replace.

Besides, "explicit is better than implicit." ;)
--
Francis Avila

Jul 18 '05 #7
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.

Peter
Jul 18 '05 #8
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
it's vital for understanding the still poorly-documented new-style classes.


documentation may also be seen as an advantage, of course.

</F>


Jul 18 '05 #9
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, 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.

More than that, you *can't* use new-style classes for exceptions. So
please stop telling people to avoid classic classes.
--
Aahz (aa**@pythoncraft.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 #10
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.
documentation 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**@pythoncraft.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**@pythoncraft.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.supernews.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 "<interactive 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).__setattr__(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.supernews.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__=type
idiom is quite safe in practice. Of course, it can give surprises,
such as the following:

__metaclass__=type

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
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...
14
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...
6
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...
4
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
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...
7
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...
3
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...
12
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...
0
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.