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#2 2>", line 1, in -toplevel-
y=f.C()
AttributeError: 'function' object has no attribute 'C'
>>>
--
Tomi Lindberg 9 7835
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#2 2>", 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
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 ;)
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
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
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#2 2>", line 1, in -toplevel-
y=f.C()
AttributeError: 'function' object has no attribute 'C'
>>
Well, you could use 'type(x)()', or object.__subcla sses__() 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'.
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
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
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
parametrization s 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 ;)
Duncan Booth <du**********@i nvalid.invalidw rote 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 class and a function in Python ???
Consider the following code fragments :
# Fragment 1 begins
a = 1
|
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 {
|
by: Neil Zanella |
last post by:
Hello,
Suppose I have some method:
Foo::foo() {
static int x;
int y;
/* ... */
}
|
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 non-standard C++ or if the
problem lies elsewhere.
To summarize static const class members are not being accessed properly
when accessed from a DLL by another external object file (not within the
DLL). It only occurs when the static const...
|
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. i would
forget overriding it but i have to do it because its a coursework. here
is a simple version of the class
#include <iostream>
#include <string>
#include <vector>
| |
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:
http://bugs.php.net/bug.php?id=15233&edit=1
Second, here's my problem:
i have a class defined. Inside that class are several LONG functions
|
by: subramanian100in |
last post by:
Consider the program
#include <iostream>
using namespace std;
class Test
{
public:
Test(Test_int c_value)
|
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 inside template class definition (commented out at //1) then
it compiles and runs fine, but if I declare and define the function
separately (at //2).
Is the following syntax supported by g++?
|
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. Most involve
passing the form into the class, or require a lot of coding. All I
really need to do is be able to have my thread call a function within
that class which runs on the same thread as the class. I've done this
from within forms, but...
|
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 in advance.
--dhina
---------------------------------------------------------------------------------------------------------------------------------------------
class Foo
{
public:
|
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...
| |
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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
|
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...
| |