473,327 Members | 1,976 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,327 software developers and data experts.

Class definition within function

Hi,

With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)? And yes, I think this is one of those times
when the real question is why :)
>>def f():
class C(object):
def __init__(self):
self.a = 'a'
return C()
>>x = f()
x.a
'a'
>>y=f.C()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in -toplevel-
y=f.C()
AttributeError: 'function' object has no attribute 'C'
>>>
--
Tomi Lindberg
Aug 2 '06 #1
9 7816
Tomi Lindberg wrote:
Hi,

With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)? And yes, I think this is one of those times
when the real question is why :)
>>def f():
class C(object):
def __init__(self):
self.a = 'a'
return C()
>>x = f()
>>x.a
'a'
>>y=f.C()

Traceback (most recent call last):
File "<pyshell#22>", line 1, in -toplevel-
y=f.C()
AttributeError: 'function' object has no attribute 'C'
No, its not. Only inside of it. And the question really is: why? If you need
a class that can be instantiated regardless of the execution of f, make it
a globally visible class. If it depends on something f computes, make it a
function-local one (if you like)

Diez
Aug 2 '06 #2

Tomi Lindberg wrote:
Hi,

With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)?
def f():
class C(object):
def __init__(self):
self.a = 'a'
f.C = C
return C()
>>f.C
<class '__main__.C'>
And yes, I think this is one of those times
when the real question is why :)
Definitely ;)

Aug 2 '06 #3
Diez B. Roggisch wrote:
No, its not. Only inside of it. And the question really is: why?
Thanks. And no need to worry, the question was intended as
fully theoretical.

--
Tomi Lindberg
Aug 2 '06 #4
Tomi Lindberg wrote:
With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)? And yes, I think this is one of those times
when the real question is why :)

*>>>*def*f():
********class C(object):
****************def __init__(self):
************************self.a = 'a'
********return C()

*>>>*x*=*f()
*>>>*x.a
'a'
y = type(x)()

By the way you get an instance of a different class C every time you call f,
so that

isinstance(f(), type(f())

is False.

Peter
Aug 2 '06 #5
Tomi Lindberg wrote:
With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)? And yes, I think this is one of those times
when the real question is why :)
>def f():
class C(object):
def __init__(self):
self.a = 'a'
return C()
>x = f()
x.a
'a'
>y=f.C()

Traceback (most recent call last):
File "<pyshell#22>", line 1, in -toplevel-
y=f.C()
AttributeError: 'function' object has no attribute 'C'
>>
Well, you could use 'type(x)()', or object.__subclasses__() will include C
for as long as the class actually exists. Choosing the correct C from
object's subclasses could prove somewhat tricky though: remember you'll get
a new C class every time you call 'f'.
Aug 2 '06 #6
Peter Otten wrote:
By the way you get an instance of a different class C every time you call f,
so that

isinstance(f(), type(f())

is False.
That I didn't know. Well, that theory won't be seeing much
practice I guess.

--
Tomi Lindberg
Aug 2 '06 #7
Kay Schluehr wrote:
>
Tomi Lindberg wrote:
>Hi,

With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)?

def f():
class C(object):
def __init__(self):
self.a = 'a'
f.C = C
return C()
>>>f.C
<class '__main__.C'>
Not working, unless f has been called at least once. But what I didn't know
(and always wondered) if the classdefinition inside a function can use the
outer scope - and apparently, it can! Cool.
def f(baseclass):
class C(baseclass):
def __init__(self):
self.a = 'a'
f.C = C
def foo(self):
print baseclass
return C()

c = f(object)
print f.C

c.foo()
Diez
Aug 2 '06 #8
Diez B. Roggisch wrote:
Kay Schluehr wrote:

Tomi Lindberg wrote:
Hi,

With the following function definition, is it possible to
create an instance of class C outside the function f (and if
it is, how)?
def f():
class C(object):
def __init__(self):
self.a = 'a'
f.C = C
return C()
>>f.C
<class '__main__.C'>

Not working, unless f has been called at least once.
Right.
But what I didn't know
(and always wondered) if the classdefinition inside a function can use the
outer scope - and apparently, it can! Cool.
Yes, the bytecode simply refers to a global name f in the scope of
__init__. Fortunately the Python compiler is too stupid to guess what f
might be but simply expects that f exists at runtime. I use this
"snake is eating itself" pattern very often for passing a module as a
reference to another module inside of itself:

--------------------- Module M
import B

def eatMe():
import M
B.m = M

if __name__ == '__main__':
eatMe()

-----------------------------------

One might consider M as a component which is definig stuff. Once you
select such a component it can be used to configure a framework F of
which B is a part ( B doesn't import M ! ) So F is essentially
parametrized by M. You ere entering the next level when different
parametrizations F(M1), F(M2),... can coexist or even refer to each
other. This isn't just a mental exercise but it's going to be the way
EasyExtend will support multiple extension languages at the same time
in the fist beta version of the program. Yes, I know ... everything is
heavily cyclic and we should do hierarchies instead ;)

Aug 2 '06 #9
Duncan Booth <du**********@invalid.invalidwrote in
news:Xn*************************@127.0.0.1:
>>def f():
class C(object):
def __init__(self):
self.a = 'a'
return C()
>>x = f()
x.a
'a'
>>y=f.C()
Of course there's this:
>>def f():
.... class C(object):
.... def __init__(self):
.... self.a = 'a'
.... return C()
....
>>x = f()
x.a
'a'
>>y=x.__class__()
y.a
'a'
>>type(y) == type(x)
True

Aug 2 '06 #10

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

Similar topics

12
by: Gaurav Veda | last post by:
Hi ! I am a poor mortal who has become terrified of Python. It seems to have thrown all the OO concepts out of the window. Penniless, I ask a basic question : What is the difference between a...
2
by: Victor Liu | last post by:
hi, why n1 in local::f() is no allowed ? int n0; void function() { int n1; static int n2; class local {
30
by: Neil Zanella | last post by:
Hello, Suppose I have some method: Foo::foo() { static int x; int y; /* ... */ }
3
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming...
2
by: franklini | last post by:
hello people i. can anybody help me, i dont know what is wrong with this class. it has something to do with the me trying to override the input output stream. if i dont override it, it works fine....
2
by: joe t. | last post by:
My apologies, i'm not sure how to ask this question correctly, so i'll give the examples as i go. First, i *think* my problem is described here, but i may be misunderstanding:...
4
by: subramanian100in | last post by:
Consider the program #include <iostream> using namespace std; class Test { public: Test(Test_int c_value)
6
by: Dan Smithers | last post by:
I want to write my own class derived from the ostream class. I have been getting errors with my templates: First, I get an error writing a nested template. If I leave the function definition...
5
by: hurricane_number_one | last post by:
I'm trying to have a class, which uses threads be able to raise events to the form that created it. I've seen solutions around the net for this, but I didn't really like their implementation. ...
28
by: cpluslearn | last post by:
Hi, I have a local class inside a function template. I am able to wrap any type in my local class. Is it legal C++? What type of class is Local? Is it a class template or regular class? Thanks...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.