In the project that I'm building, I'd like to have a method called when I paste some text into a specific text field. I can't seem to get this to work, but here's what I've tried
I implimented a custom class (based on NSObject) to be a delegate for my textfield, then gave it the method: textDidChange:
class textFieldDelegate(NSObject):
def textDidChange_(self, notification):
NSLog("textdidchange")
I then instantiated an object of this class in interface builder, and set it to be the delegate of the NSTextField. This however, doesn't seem to do anything. However, when I build the example code from http://www.programmish.com/?p=30, everything seems to work perfectly fine. How do I impliment this delegate code so that it actually works?
The reason this isn't working for you is that textDidChange_ isn't a delegate method. It's a method on the NSTextField that posts the notification of the change. If you have peek at the docs for textDidChange, you'll see that it mentions the actual name of the delegate method:
This method causes the receiver’s delegate to receive a controlTextDidChange: message. See the NSControl class specification for more information on the text delegate method.
The delegate method is actually called controlTextDidChange_ and is declared on the NSTextField superclass, NSControl.
Change your delegate method to:
def controlTextDidChange_(self, notification):
NSLog("textdidchange")
and it should work for you.
Related
I am struggling to understand when it makes sense to use an instance method versus a static method. Also, I don't know if my functions are static since there is not a #staticmethod decorator. Would I be able to access the class functions when I make a call to one of the methods?
I am working on a webscraper that sends information to a database. It’s setup to run once a week. The structure of my code looks like this
import libraries...
class Get:
def build_url(url_paramater1, url_parameter2, request_date):
return url_with_parameters
def web_data(request_date, url_parameter1, url_parameter2): #no use of self
# using parameters pull the variables to look up in the database
for a in db_info:
url = build_url(a, url_parameter2, request_date)
x = requests.Session().get(url, proxies).json()
#save data to the database
return None
#same type of function for pulling the web data from the database and parsing it
if __name__ == ‘__main__’:
Get.web_data(request_date, url_parameter1, url_parameter2)
Parse.web_data(get_date, parameter) #to illustrate the second part of the scrapper
That is the basic structure. The code is functional but I don’t know if I am using the methods (functions?) correctly and potentially missing out on ways to use my code in the future. I may even be writing bad code that will cause errors down the line that are impossibly hard to debug only because I didn’t follow best practices.
After reading about when class and instance methods are used. I cannot see why I would use them. If I want the url built or the data pulled from the website I call the build_url or get_web_data function. I don’t need an instance of the function to keep track of anything separate. I cannot imagine when I would need to keep something separate either which I think is part of the problem.
The reason I think my question is different than the previous questions is: the conceptual examples to explain the differences don't seem to help me when I am sitting down and writing code. I have not run into real world problems that are solved with the different methods that show when I should even use an instance method, yet instance methods seem to be mandatory when looking at conceptual examples of code.
Thank you!
Classes can be used to represent objects, and also to group functions under a common namespace.
When a class represents an object, like a cat, anything that this object 'can do', logically, should be an instance method, such as meowing.
But when you have a group of static functions that are all related to each other or are usually used together to achieve a common goal, like build_url and web_data, you can make your code clearer and more organized by putting them under a static class, which provides a common namespace, like you did.
Therefore in my opinion the structure you chose is legitimate. It is worth considering though, that you'd find static classes more in more definitively OOP languages, like Java, while in python it is more common to use modules for namespace separation.
This code doesn't need to be a class at all. It should just be a pair of functions. You can't see why you would need an instance method because you don't have a reason to instantiate the object in the first place.
The functions you have wrote in your code are instance methods but they were written incorrectly.
An instance method must have self as first parameter
i.e def build_url(self, url_paramater1, url_parameter2, request_date):
Then you call it like that
get_inst = Get()
get_inst.build_url(url_paramater1, url_parameter2, request_date)
This self parameter is provided by python and it allow you to access all properties and functions - static or not - of your Get class.
If you don't need to access other functions or properties in your class then you add #staticmethod decorator and remove self parameter
#staticmethod
def build_url(url_paramater1, url_parameter2, request_date):
And then you can call it directly
Get.build_url(url_paramater1, url_parameter2, request_date)
or call from from class instance
get_inst = Get()
get_inst.build_url(url_paramater1, url_parameter2, request_date)
But what is the problem with your current code you might ask?
Try calling it from an instance like this and u will see the problem
get_inst = Get()
get_inst.build_url(url_paramater1, url_parameter2, request_date)
Example where creating an instance is useful:
Let's say you want to make a chat client.
You could write code like this
class Chat:
def send(server_url, message):
connection = connect(server_url)
connection.write(message)
connection.close()
def read(server_url):
connection = connect(server_url)
message = connection.read()
connection.close()
return message
But a much cleaner and better way to do it:
class Chat:
def __init__(server_url):
# Initialize connection only once when instance is created
self.connection = connect(server_url)
def __del__()
# Close connection only once when instance is deleted
self.connection.close()
def send(self, message):
self.connection.write(message)
def read(self):
return self.connection.read()
To use that last class you do
# Create new instance and pass server_url as argument
chat = Chat("http://example.com/chat")
chat.send("Hello")
chat.read()
# deleting chat causes __del__ function to be called and connection be closed
delete chat
From given example, there is no need to have Get class after all, since you are using it just like a additional namespace. You do not have any 'state' that you want to preserve, in either class or class instance.
What seems like a good thing is to have separate module and define these functions in it. This way, when importing this module, you get to have this namespace that you want.
I have next class:
#implementer(ISocial)
class SocialVKSelenium:
pass
And when I add it to zope registry:
gsm = getGlobalSiteManager()
gsm.registerAdapter(SocialVKSelenium)
I got: TypeError: The adapter factory doesn't have a __component_adapts__ attribute and no required specifications were specified
When I add there adapter(IOther), the registration works as expected, but without is not. Why does it happens?
You need to provide a context, either on the class, or to the registry.
I suspect that you are not communicating the entirety of your problem set -- an adapter is a component that adapts an object of a specified interface, and provides another. Your example fails to specify what the context being adapted is, that is, what kind of object is adapted on construction of your adapter object by its class?
For example, this works fine:
from zope.interface import Interface, implements
from zope.component import getGlobalSiteManager, adapts
class IWeight(Interface):
pass
class IVolume(Interface):
pass
class WeightToVolume(object):
implements(IVolume)
adapts(IWeight)
#...
gsm = getGlobalSiteManager()
gsm.registerAdapter(WeightToVolume)
While you can use the decorator (implementer/adapter) syntax for this, by convention, use of implements/adapts are preferred for adapter factories that are classes, not functions.
At the very minimum if your adapter does not declare what it adapts on the class or factory function itself, you will need to tell the registry. In the broadest case, this might look like:
gsm.registerAdapter(MyAdapterClassHere, required=(Interface,))
Of course, this example above is an adapter that claims to adapt any context, which is not recommended unless you know why you need that.
I am learning wxPython. In one of the examples, the code is like follows:
import wx
class App(wx.App):
def OnInit(self):
frame = wx.Frame(parent=None, title = 'bare')
frame.Show()
return True
app=App()
app.MainLoop()
And I noticed that class App has no constructor but a function OnInit. As far as I know, Python classes are constructed with __init__ function.
So, is OnInit functions are for specific classes? Or it is another type of constructor?
Please forgive my ignorance since I am new to this. Thanks.
According to wx.App.__init__ documentation:
You should override OnInit to do applicaition initialization to ensure
that the system, toolkit and wxWidgets are fully initialized.
-> OnInit method is only for classes that derive wx.App.
Assuming you got the code from "wxPython in Action" book- good book would recommend,
It goes on to say (Im sure you have red this by now)...
Notice that we didn’t define an init()method for our application
class. In Python, this means that the parent method,
wx.App.init(), is automatically invoked on object creation. This
is a good thing. If you define an init() method of your own, don’t
forget to call the init()of the base class, like this:
class App(wx.App):
def __init__(self):
# Call the base class constructor.
wx.App.__init__(self)
# Do something here...
If you forget to do so, wxPython won’t be initialized and your OnInit()method won’t get called.
I am trying to extend a Python library to add functionality I desire. The library provides a number of HTML form objects (such as Textbox, Dropdown, Checkbox, etc.), all derived from an Input object. I want to add an additional attribute to all of these derived objects. What is the proper way of proceeding?
I can:
Modify the original source code for the Input class, adding the attribute I want.
Create a new class that inherits Input and adds my attribute, and then create a bunch of new classes that inherit Textbox, Dropdown, and my new Input class.
Create new classes for Textbox, Dropdown, etc. with the attribute.
Solution 1 is the easiest and simplest, but is inherently wrong, whereas the other two seem like much more work and code-repetition than this task should call for.
Is there a solution I'm missing?
The 4th solution is monkey patching and might be a good idea. Before you try this, make sure this won't break anything now or in the future:
def additional_method(self, arg):
print("hello", arg)
Input.additional_method = additional_method
or for short stuff:
Input.additional_method = lambda self, arg: do_something(arg)
now all existing and future Input instances (and therefore instances of all Input subclasses) have an additional_method attached to them.
This works also for any future subclasses of Input that might not even exist yet, or you might not be aware of, at the time of adding the method, so is therefore better (i.e. more generic) than creating an alternative inheritance hierarchy, which you'll have to then maintain and keep in sync with upstream changes.
NOTE: before you downvote just because it contains the phrase "monkey patching", consider that monkey patching doesn't have to be dangerous/fragile, and is a first class (as in "respected") feature in many languages.
You can use a mixin (multiple inheritance). It's a class that just contains your extra attribute, and add this class to the parent class of a subclass of Textbox, Dropdown, Checkbox... like this:
from ... import TextBox
class Mixin:
def __init__(self):
self.new_attribude = ...
class TextBox_with_new_attribute(Mixin, TextBox):
pass
But, it depends tightly on your goals...
Edit: base on #Veedrac comment, in case of third party library.
If there are a lot of classes you could dynamically apply a mixin:
for cls in list_of_classes_to_patch:
patched = type(cls.__name__, (my_mixin, cls), {})
setattr(place_to_export, cls.__name__, patched)
place_to_export can be defined as import this_module as place_to_export.
I am trying to learn PyQt on my own from rapid gui programming with python and qt and having trouble understanding the meaning/requirement of below line of code mentioned in one of the example in the book.
class Form(QDialog):
def __init__(self,parent=None):
super(Form,self).__init__(parent) # Trouble understanding here
So, my question is what is the need of super(Form,self).__init__(parent) or what purpose it is trying to full fill in this code.
Take a look at the documentation of super():
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
So basically this line of code:
super(Form,self).__init__(parent)
finds the "closest" set __init__() method in classes from which current class (Form) is inheriting and initiates self object using this method and passing parent as the first argument.