473,657 Members | 2,531 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I'm having trouble understanding scope of a variable in a subclass

Approach 1:

class Class1:
class Class2:
def __init__(self): self.variable=" variable"

class Class3:
def method():print Class1().Class2 ().variable #problem

Approach 1.1:

class Class1:
class Class2:
def __init__(self): self.variable=" variable"

class Class3:
def method():print Class1.Class2.v ariable #problem

Approach 2:

class Class1:
class Class2:
variable="varia ble"

class Class3:
def method():print Class1().Class2 ().variable #problem

Approach 2.1:

class Class1:
class Class2:
variable="varia ble"

class Class3:
def method():print Class1.Class2.v ariable #problem

Is there a correct solution in the above? Or, what is the solution?
Dec 28 '06 #1
9 1418
class Class1:
class Class2(Class1):
variable="varia ble"
class Class3(Class2):
print Class1().Class2 ().variable #problem

Also, why is this wrong?
Dec 28 '06 #2
On Thu, 28 Dec 2006 15:31:26 +1100, Pyenos wrote:
Approach 1:

class Class1:
class Class2:
def __init__(self): self.variable=" variable"

class Class3:
def method():print Class1().Class2 ().variable #problem
These are NESTED classes, not subclasses.

You say "#problem". What's the problem? What does it do that you don't
expect, or not do that you do expect? Does it crash your PC? Raise an
exception? Don't assume that we can guess what the problem is.

[snip multiple attempts]
Is there a correct solution in the above? Or, what is the solution?
The solution to what problem? What are you trying to do? Why are you
nesting classes? Nesting classes isn't wrong, but it is quite advanced.
Let's do subclassing first.

class Parrot(object):
"""Parrot class."""
plumage = "green" # The default colour of parrots.
def __repr__(self):
return "A parrot with beautiful %s plumage." % self.plumage

class NorwegianBlue(P arrot):
"""Norwegia n Blue class, subclass of Parrot."""
plumage = "blue"
Now experiment with those two classes:
>>p = Parrot()
p
A parrot with beautiful green plumage.
>>p.plumage = "red" # Change the instance.
p
A parrot with beautiful red plumage.
>>Parrot() # But the class stays the same.
A parrot with beautiful green plumage.
>>q = NorwegianBlue()
q
A parrot with beautiful blue plumage.
>>q.plumage
'blue'
>>super(Norwegi anBlue, q).plumage
'green'
Does this help?
--
Steven D'Aprano

Dec 28 '06 #3
Thanks for clarifying the definitions of nested class and
subclass. However, it did not solve my original problem, and I have
redefined my question:

class Class1:
class Class2:
class Class3:
def __init__(self):
self.var="var"
class Class4:
print Class1.Class2.C lass3.var

This code gives me the error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in Class1
File "<stdin>", line 3, in Class2
File "<stdin>", line 6, in Class3
File "<stdin>", line 7, in Class4
NameError: name 'Class1' is not defined

I have tried:

class Class1:
class Class2:
def __init__(self):
var="var"
print Class1.Class2() .var #this works

And, this worked. It is very strange that nested loop somehow fails to
work when the innermost class has indentation level greater than two.
Dec 28 '06 #4
Pyenos <py****@pyenos. orgwrites:
Thanks for clarifying the definitions of nested class and
subclass. However, it did not solve my original problem, and I have
redefined my question:

class Class1:
class Class2:
class Class3:
def __init__(self):
self.var="var"
class Class4:
print Class1.Class2.C lass3.var

This code gives me the error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in Class1
File "<stdin>", line 3, in Class2
File "<stdin>", line 6, in Class3
File "<stdin>", line 7, in Class4
NameError: name 'Class1' is not defined

I have tried:

class Class1:
class Class2:
def __init__(self):
var="var"
print Class1.Class2() .var #this works

And, this worked. It is very strange that nested loop somehow fails to
work when the innermost class has indentation level greater than two.
I found this link which is relevent:
http://mail.python.org/pipermail/pyt...il/198978.html

Dec 28 '06 #5
Hello,

Pyenos a écrit :
Thanks for clarifying the definitions of nested class and
subclass. However, it did not solve my original problem, and I have
redefined my question:

class Class1:
class Class2:
class Class3:
def __init__(self):
self.var="var"
class Class4:
print Class1.Class2.C lass3.var

This code gives me the error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in Class1
File "<stdin>", line 3, in Class2
File "<stdin>", line 6, in Class3
File "<stdin>", line 7, in Class4
NameError: name 'Class1' is not defined

I have tried:

class Class1:
class Class2:
def __init__(self):
var="var"
print Class1.Class2() .var #this works

And, this worked. It is very strange that nested loop somehow fails to
work when the innermost class has indentation level greater than two.
This has nothing to do with the indentation level.
But please try to copy exactly the code that you actually executed.

- Your first example fails, but with a different error message
(hint: the "print" statement is not inside a function, so it is executed
as soon as the interpreter sees it - before it defines the classes.)
And it differs with your second example because the parentheses are
missing after the name "Class3".

- Your second example does not work as you say. 'var' is a local
variable and cannot be accessed from the outside. I suppose you actually
entered something like:
self.var="var"
which works indeed.

Again, it is difficult to guess what you are trying to do.

--
Amaury
Dec 28 '06 #6
At Thursday 28/12/2006 01:31, Pyenos wrote:
class Class3:
def method():print Class1.Class2.v ariable #problem
In all your examples, you wrote def method() instead of def method(self).
Error messages are usually meaningful, they give you valuable
information, try to interpret them.
>Is there a correct solution in the above? Or, what is the solution?
You have not stated what is your problem, so it's difficult to give a solution.
Why do you think you may need a nested class (*not* subclass)? What
are you trying to do? I bet you don't need a nested class at all.
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Dec 28 '06 #7
At Thursday 28/12/2006 01:39, Pyenos wrote:
>class Class1:
class Class2(Class1):
variable="varia ble"
class Class3(Class2):
print Class1().Class2 ().variable #problem

Also, why is this wrong?
Again, don't write just "problem"!
What do you want do do? Writing random statements at random order and
random indentation levels is not the best way to learn Python (nor anything!)

Defining a nested class which itself inherits from its container
*might* make *some* sense in very specific circunstances, but
certainly is *not* a recommended newbie practice.
It's like using the accelerator and brake at the same time when
driving - an experienced driver *might* do that in certain
circunstances, but if you are learning to drive, you either
accelerate or either use the brake but NOT both.
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Dec 28 '06 #8
At Thursday 28/12/2006 03:18, Pyenos wrote:
>class Class1:
class Class2:
class Class3:
def __init__(self):
self.var="var"
class Class4:
print Class1.Class2.C lass3.var

This code gives me the error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in Class1
File "<stdin>", line 3, in Class2
File "<stdin>", line 6, in Class3
File "<stdin>", line 7, in Class4
NameError: name 'Class1' is not defined
- put your print statement inside a method
- as I've said, try to grab the difference between an instance
attribute and a class attribute.

var is an attribute of Class3 instances (because you wrote self.var =
something), so you need a Class3 instance to access it.
Class3 is a class attribute of Class2. Class2 is an instance
attribute of Class1. Putting all this together, you can refer to such
"var" as Class1.Class2.C lass3().var
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Dec 28 '06 #9

Pyenos wrote:
Approach 1:

class Class1:
class Class2:
def __init__(self): self.variable=" variable"

class Class3:
def method():print Class1().Class2 ().variable #problem

Approach 1.1:

class Class1:
class Class2:
def __init__(self): self.variable=" variable"

class Class3:
def method():print Class1.Class2.v ariable #problem
Approach 2:

class Class1:
class Class2:
variable="varia ble"

class Class3:
def method():print Class1().Class2 ().variable #problem
Approach 2.1:

class Class1:
class Class2:
variable="varia ble"

class Class3:
def method():print Class1.Class2.v ariable #problem

Is there a correct solution in the above? Or, what is the solution?
Your definition of Class3.method() shall have a 'self' argument, then
the above will all be ok.

Dec 29 '06 #10

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

Similar topics

2
4541
by: Jozef | last post by:
Hello, I am trying to put together a module and open a workspace on a database that has a simple password (using Access XP). This is the lin that I'm having trouble with; Set wrk = CreateWorkspace("TestWrkspc", "Admin", conDbPwd) conDBPwd is a variable that contains the password. There is no independant workgroup file, just the default. This is the error message I'm getting;
7
3308
by: | last post by:
I fail to understand why that the memory allocated in the void create(int **matrix) does not remain. I passed the address of matrix so shouldn't it still have the allocated memory when it returns to main. The problem i am having is understanding why the printf statement in the code below gives the value. I would have expected it to be 123 which is the value I set it to in the create. Thanx in advance. void create(int **matrix); int...
5
2506
by: Krumble Bunk | last post by:
Hello! First things first (but not necessarily in that order), this is a really great group, and has helped me understand more and more C everytime I read the postings, so thanks for a great learning environment! I am having difficulty understanding this bitwise macro (i've recently moved into working on these, using OpenSolaris source code - magnificent learning resource btw!)
7
9684
by: Mike Joseph | last post by:
I have a data file that was produced in MicroSoft Access. It's a table that was exported as a fixed format, sequential access ASCII file. It contains over 80,000 records. Basically, all the stats for every player in Major League Baseball history in alphabetical order and then by each year they played. I want to take this data and display to the user the career totals for each player. I don't seem to understand how to use StreamReader...
3
1349
by: RSH | last post by:
I am slowly getting the hang of objects and creating my own. I was given some help in assigning an object to a ComboBox collection. I have been looking at it and I get the concept which is very powerful but I'm having a bit of a problem conceptually. I was hoping someone might be able to shed some light on creating this object and assigning it in the manner. Also how would I reference this object by name after it is created in this...
6
8338
by: shaun | last post by:
If I put (define) const variables at the top of a .cpp file but do not declare them in the .h file, are they only visible within that .cpp file? e.g. const int a={1,2,3,4}; in a cpp file will be a 'global' with file scope? (no flames for oxymoron, please), available for use inside my functions which are defined in the same file (but which are also declared in the .h)?
3
5423
by: Jake Barnes | last post by:
I thought I understood this article: http://simon.incutio.com/archive/2004/05/26/addLoadEvent It seems like a smart, insightful function: function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') {
3
1852
by: livesinabox | last post by:
I am a student and I am having trouble understanding Dynamic Memory Allocation and the usage of Double Pointers. int **A A=(int **)malloc(r1*(sizeof(int*))); for(i=0;i<r1;i++) A=(int *)malloc(sizeof(int)*c1)
2
1631
by: Casey Daniels | last post by:
I'm new to Java, and for the life of me I don't understand the whole inheritance concept apparently. I'm trying to create and exit button on a JWindow. my main Class reads like this public static void main(String args) { JWindow MainWindow = new JWindow(); MainWindow.setVisible(true); MainWindow.setSize(500,500); MainWindow.setLocation(100,100); ExitButton Fred = new ExitButton();
0
8420
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
8324
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
8842
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
8740
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...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5642
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();...
0
4173
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...
1
2743
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
2
1733
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.