This question already has answers here:
Nested Python class needs to access variable in enclosing class
(6 answers)
Closed 8 years ago.
I'm trying to assign a variable in my inner class with the variable on the outer class.
class OUTER(QtGui.QWidget):
def __init__(self):
super (OUTER, self).__init__()
self.initUI()
def number (self):
self.out = 50
...
class INNER(QtGui.QLCDNumber)
in = OUTER.out #error: NameError: name 'OUTER' is not defined
#pyqtSlot()
def some_func(self):
self.display(self.in)
I'm getting an error
NameError: name 'OUTER' is not defined.
Is there any way to fix this?
You can't do this.
OUTER is not defined until the entire outer class declaration is finished. Class bodies are executable code; they are executed at definition time. When the body is defined, it is allocated to the name, but until then the name does not exist.
That is one of the reasons why nesting classes is rarely a good idea in Python. The inner class does not get any special access to the outer class, so there isn't really any reason to nest them at all.
Plus, I've just noticed that you are trying to refer to an instance variable via a class. That can't ever work. OUTER.out does not exist, only instances of OUTER have an out attribute. (What would the value of OUTER.out even be?)
Related
This question already has answers here:
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 1 year ago.
I know that some of you will think It's a stupid question but I will ask anyway.
why do we need to pass 'self' on all class methods can't we use it without passing it like this:
class Player:
def __init__(name):
self.name = name
def print_player_name():
print(self.name)
Try it. It won't work because self is not defined. The name "self" is just established, but you could name it whatever you want. It refers to the object of the class on which the method is called.
Yes, you can do it but you have to mention it as a static method. Self represents the instance of the class. In simple words, self represents the object on which it is being executed. When you create an object, all variables change their values based on different object of same class. Every class needs object as it's argument because for different object, different values are assigned
self represents object of class on which method is called you don't always need to name it self[standard convention] any valid variable name is allowed in python to do this but it should be first argument of non-classmethods and should be replace self as in if you run this python will work as expected :
class Player:
def __init__(hello, name):
hello.name = name
def print_player_name(hello):
print(hello.name)
It's very simple that's the official Python convention. In official docs we can read about it.
"Often, the first argument of a method is called self. This is nothing
more than a convention: the name self has absolutely no special
meaning to Python. Note, however, that by not following the convention
your code may be less readable to other Python programmers, and it is
also conceivable that a class browser program might be written that
relies upon such a convention."
This question already has answers here:
What is a mixin and why is it useful?
(18 answers)
Closed 2 years ago.
class SoftDeleteMixin(object):
deleted_at = Column(DateTime)
deleted = Column(types.SoftDeleteInteger, default=0)
def soft_delete(self, session):
"""Mark this object as deleted."""
self.deleted = self.id
self.deleted_at = timeutils.utcnow()
self.save(session=session)
In class SoftDeleteMixin method soft_delete, it references nonexistent self.id and self.save. Why can it do that in python?
Note: the focus is the class can reference nonexistent variable and method, not that it is a Mixin class.
If you instantiate a SoftDeleteMixin class and call the soft_delete method, you'll get an AttributeError.
If as you said in the comment those attributes are instantiated somewhere else, even in a child class, and you call soft_delete on a child class instance, it works because the attribute is there at the time the method is called.
To explain it in a simple way, python is an interpreted language, and except for syntax it does not perform too much checks on the whole file when executing the code, until that actual line is actually executed.
So yes, you could think it's a bad design but it is not, it's an accepted practice (see this question for more details) and it is allowed by the laguage. You can define methods which reference attributes not defined in a __init__ method or as class attributes or whatever. The important thing is that the istance has the attribute when the method is executed. It does not matter where or when the attribute is actually defined.
The word "mixin" in the class name means that this class is intended to be inherited by a class that already declares id and save(). If you try to use it by itself, it will cause errors.
This question already has answers here:
python subclass access to class variable of parent
(2 answers)
Closed 6 years ago.
In Python, when defining a class it's possible to use previously defined attributes in new attributes definition without any further reference.
class Parent(object):
a_value = 'a'
another_value = 'b'
all_values = (a_value, another_value)
Is it possible to do the same in a derived class but still accessing some of these parent attributes?
I tried doing something like this:
class Child(Parent):
a_child_value = 'c'
all_values = (a_value, another_value, a_child_value)
But it seems that it doesn't take into account the Parent inheritance and gives me the following error:
NameError: name 'a_value' is not defined
So, is there any way to indicate that the a_value and another_value should be from the parent class instead of the current context?
In my case in particular the values are not strings but rather pre-compiled regular expressions, so I would like to avoid having to create them inside the __init__ method every time a new instance is created.
like this.
class Child(Parent):
a_child_value = 'c'
all_values = (Parent.a_value, Parent.another_value, a_child_value)
You need to do Parent.a_value in order to get the value you are after. a_child is a static attribute and therefore attached to the class itself and not a local variable.
class Child(Parent):
a_child_value = 'c'
all_values = (Parent.a_value, Parent.another_value, a_child_value)
If it is derived from something, you HAVE to type what it is derived from.
This question already has answers here:
Python class attribute referencing
(2 answers)
Closed 7 years ago.
Is it possible to access self.bin outside the class?
class kon():
def __init__(self):
pass
def add(self):
con=7
self.bin=100
h=kon()
bin=h.bin
In one topic advised to use self. before variables but it did not work.
Maybe such variables must be in __init__ method.
You have to read docs. It will be very useful for you.
The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named init(), like this:
def __init__(self):
self.bin = 0
When a class defines an init() method, class instantiation automatically invokes init() for the newly-created class instance.
After this you can use this property in you object, to read or assign value.
Also, there is a difference between initialize properties in the class. From the docs:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 9 years ago.
Look at the code below:
class Node:
feature = list()
label = list()
def __init__(self, f, l):
self.feature.append(f)
self.label.append(l)
I create two instances of this class:
n1 = Node(1,2)
print n1.feature
n2 = Node(3,4)
print n2.feature
My desired output is:
1
2
But the real output is:
1
1 2
What is the problem? How can I fix it?
variables defined in class scope are class variables, and are share among all class instances (they are stored on the class object itself, not on the instances).
Just initialize the variables inside the init function.
class Node:
def __init__(self, f, l):
self.feature = [f]
self.label = [l]
The issue is that you're trying to "declare" the member data for the class instances in the class block. That's not how Python works.
Everything defined in the class block (including feature, label, and __init__) becomes an attribute of the object that represents the class itself, not the instances of the class. Trying to access an attribute that doesn't exist in an instance will fall back to the class, which is how method lookup works.
There is no way to create a attribute on an instance until it exists and you have a reference to it. The purpose of the __init__method is to give you a place to do that. So initial values for an instance's member data should be set up in __init__; trying to declare these initial values in the class block actually does something else.