When is "self" required?

I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.

However, I'm looking through the wxPython in Action book and notice that "self" isn't used all the time. For example:

 import wx
 class TextFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Text Entry Example',
            size=(300, 100))
        panel = wx.Panel(self, -1)
        basicLabel = wx.StaticText(panel, -1, "Basic Control:")
        basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
            size=(175, -1))
        basicText.SetInsertionPoint(0)
        pwdLabel = wx.StaticText(panel, -1, "Password:")
        pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
            style=wx.TE_PASSWORD)
        sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
        sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
        panel.SetSizer(sizer)

The one below does use "self".

import wx
class ButtonFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Button Example',
            size=(300, 100))
        panel = wx.Panel(self, -1)
        self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
        self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
        self.button.SetDefault()
    def OnClick(self, event):
        self.button.SetLabel("Clicked")

If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?


Asked by: Eric503 | Posted: 01-10-2021






Answer 1

You use self.attribute to reference an attribute of your current instance.

You use wx.Frame.__init__() to reference a method of the parent class.

You don't use self if you only reference a local name (variable) of the method (function) you are in.

These are not "rules of thumb," because there are no exceptions.


What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.

If you look at the documentation to wx.Panel, though, you will see that its constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.

Magic :)

Answered by: Kirsten513 | Posted: 02-11-2021



Answer 2

In those instances, if you do not use self then you will create only a local variable of that name. In the first example, panel is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing self to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns.

Answered by: Freddie137 | Posted: 02-11-2021



Answer 3

self is always required when referring to the instance itself, except when calling the base class constructor (wx.Frame.__init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all. These names will be gone when the method returns - everything put into self.foo will survive the end of the method, and be available in the next method (e.g. self.button).

Answered by: Thomas109 | Posted: 02-11-2021



Similar questions

Is it required to learn Python 2.6 along with Python 3.0?

If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? Remarkably similar to: If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?


python - Django required field in model form

I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py class CircuitForm(ModelForm): class Meta: model = Circuit exclude = ('lastPaged',) def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) self.fields['begin'].widget = widgets.AdminSplitDateTime() self.f...


python - Move required files where they need to go

I'm working on a Python script that unzips a compressed directory and installs some files. When you unzip the compressed file, there could be files like ./usr/bin/package or ./var/lib/package. The unzipped directory contains the names of the dirs where they actually need to go. Lets say the directory structure looks like: ./zippedfile.zip ./usr /bin /package ./var ./lib...


python - How to add an app to django admin site which do not required model?

How to add an app to django admin site which do not required model? I mean I need to make inteface for my app. But i dont want to create any tables in databas. Actually it going to work with solr items. Or maybe someone knows any dummy model which acts like a real model.. but is not related with database table? So then i can overwrite admin templates.


python - How to get required data from the string


python - is snmp required

is snmp really required to manage devices ? i'd like to script something with python to manage devices (mainly servers), such as disk usage, process list etc. i'm learning how to do and many article speak about snmp protocole. I can't use, for example, psutil, or subprocess or os modules, and send information via udp ? Thanks a lot


python - This field is required error in django

In the model I set: class Task(models.Model): EstimateEffort = models.PositiveIntegerField('Estimate hours',max_length=200) Finished = models.IntegerField('Finished percentage',blank=True) But in the web page, if I didn't set a value for the Finished field, it is showing an error This field is required. I tried null=True and blank=True


python - How to find out the required window size?

I have a window containing a label w whose text can be any of a given variety (in this case "Hello World! " once, twice and thrice): from Tkinter import * import time root = Tk() text = "Hello, World! " w = Label(root) for i in range(1, 4): w["text"] = text*i w.update_idletasks() w.grid() w.update_idletasks() time.sleep(1) root.mainloop() I would like to set the siz...


How to use python to parse XML to required custom fields

I've got a directory full of salesforce objects in XML format. I'd like to identify the <fullName> and parent file of all the custom <fields> where <required> is true. Here is some truncated sample data, lets call it "Custom_Object__c: <?xml version="1.0" encoding="UTF-8"?> <CustomObject xmlns="http://soap.sforce.com/2006/04/metadata"> &...


regex - copy required data from one file to another file in python

I am new to Python and am stuck at this I have a file a.txt which contains 10-15 lines of html code and text. I want to copy data which matches my regular expression from one a.txt to b.txt. Suppose i have a line Hello "World" How "are" you and I want to copy data which is between double quotes i.e. World and are to be copied to new file.


Is it required to learn Python 2.6 along with Python 3.0?

If I learn python 3.0 and code in it, will my code be still compatible with Python 2.6 (or 2.5 too!)? Remarkably similar to: If I'm Going to Learn Python, Should I Learn 2.x or Just Jump Into 3.0?


python - How do i extract my required data from HTML file?

This is the HTML I have: p_tags = '''<p class="foo-body"> <font class="test-proof">Full name</font> Foobar<br /> <font class="test-proof">Born</font> July 7, 1923, foo, bar<br /> <font class="test-proof">Current age</font> 27 years 226 days<br /> <font class="test-proof">Major teams</font> <span style="white-space: nowrap"&gt...


python - An integer is required? open()

I have a very simple python script that should scan a text file, which contains lines formatted as id='value' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r') for line in val_f: t = line.split('=') t[1].strip('\'') ...


python - Django required field in model form

I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py class CircuitForm(ModelForm): class Meta: model = Circuit exclude = ('lastPaged',) def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) self.fields['begin'].widget = widgets.AdminSplitDateTime() self.f...


Python required variable style

What is the best style for a Python method that requires the keyword argument 'required_arg': def test_method(required_arg, *args, **kwargs): def test_method(*args, **kwargs): required_arg = kwargs.pop('required_arg') if kwargs: raise ValueError('Unexpected keyword arguments: %s' % kwargs) Or something else? I want to use this for all my methods in the future so I'm kind...


command line - Python: How to make an option to be required in optparse?

I've read this http://docs.python.org/release/2.6.2/library/optparse.html But I'm not so clear how to make an option to be required in optparse? I've tried to set "required=1" but I got an error: invalid keyword arguments: required I want to make my script require --fi...


python - how to make django comment model field Site not required

I'm using django-threadedcomments from ericflo on github. This app simply extends the native django comments framework. I am running into the same issue with both frameworks. I continue to get an error relating to mysql that site_id cannot be null. I have no use for the Site field in my comments. I tried to extend the Comment model with my own making site both blank and null but I am still getting the same error. Wha...


python - Move required files where they need to go

I'm working on a Python script that unzips a compressed directory and installs some files. When you unzip the compressed file, there could be files like ./usr/bin/package or ./var/lib/package. The unzipped directory contains the names of the dirs where they actually need to go. Lets say the directory structure looks like: ./zippedfile.zip ./usr /bin /package ./var ./lib...


python - How to make a many to many or a foreign key not required in a model for django?

here is my model : class Page(models.Model): template = models.CharField(max_length=200,blank=True) self_url = models.ForeignKey('liens.Lien',null=True,blank=True) Categorie = models.ForeignKey(Categorie_Page,null=True,blank=True) Liens = models.ManyToManyField('liens.Lien',related_name="Liens sur la page",null=True,blank=True) Nom = models.CharField(max_length=200) ImagesSite = mode...


python - How to add an app to django admin site which do not required model?

How to add an app to django admin site which do not required model? I mean I need to make inteface for my app. But i dont want to create any tables in databas. Actually it going to work with solr items. Or maybe someone knows any dummy model which acts like a real model.. but is not related with database table? So then i can overwrite admin templates.






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top