Class coding and usage - Python Help - Discussions on Python.org
Class coding and usage Python Help RFC rob42 (Rob) April 9, 2023, 1:05pm 1 I’m trying to extend my Python skills and feel that I need to tackle the subject of Classes. I’ve read a few tutorials, but none of them seem to deal with the topic in a way that I can fully relate to. By pure coincidence this post popped up which seemed to me to be a project to which I could apply a ‘Class’. Rather than hijack that thread, I thought it better to create this RFC thread.
This is a working example of what I’ve coded: import csv class movie: def __init__(self, title, director, year): self.title = title self.director = director self.year = year # this would be a csv file read in fact, rather than a hard coded object data = ( "Scarface,Brian De Palma,1983", "Reservoir Dogs,Quentin Tarantino,1992", "Jackie Brown,Quentin Tarantino,1997", "Pulp Fiction,Quentin Tarantino,1994", "Monty Python's Life of Brian,Terry Jones,1979", "American Gangster,Ridley Scott,2007" ) movies = {} #===============<data loader>================# for enrty in data: read = csv.reader(data) for entry in read: title = entry[0] director = entry[1] year = entry[2] key = title.replace(" ", "_") movies[key] = movie(title, director, year) #=============<end of data loader>============# Now, the details of any movie can be accessed in the usual way… print(movies['Pulp_Fiction'].title) print(movies['Scarface'].director) … and so on.
The RFC is for how I’ve coded this and is it a good example of, not only how to code a Class, but also the usage of said. This is my first attempt at coding/using a custom Class in any app, so please be fair, but also honest. Thank you. Rosuav (Chris Angelico) April 9, 2023, 2:11pm 2 Before looking at creating your own classes, it’s worth taking some time to understand the classes that already exist. I’m going to use the built-in integer class as an example here.
What can you do with integers? You can create them and print them out: x = int("1A2B3", 16) print(x) # displays: 107187 They have attributes, although not particularly exciting ones here: print(x.real, x.imag) # prints the number itself, and zero for the imaginary part) And they have methods, which are “function attributes” if you like: binary = x.to_bytes(4, "big") # is the bit string b'\x00\x01\xa2\xb3' Integers also respond to operators, although not all classes have to: x = 5 * 7 # x is now 35 Great!
So, how can you make your own type? First off, you define a class. You then usually want to define how you create them, which you’ve done with your __init__ method. That right there is a great clue as to how Python lets you hook into different parts of the language: create a method that begins and ends with a double underscore. So, how’s your movie class looking? Pretty good so far, in fact. The only trouble is, it’s not really much of a class.
So the next real question is: what can you do with a movie? You have some attributes, but without anything else, your class is just a storage area or dump space. What methods would a movie have? Would it respond to operators? For example, you could have movies respond to comparison operators, such as: "Luke Skywalker" in movies["Star Wars: A New Hope"] # returns True because the character is present "Jar Jar Binks" in movies["Star Wars: A New Hope"] # returns False, because mistakes that bad weren't made until the prequel trilogy Or you could have a movie.watch() method that locates the movie on a streaming service you have a subscription to, and launches your web browser to let you watch that movie.
Or whatever makes sense for what you’re doing. So, the short answer is: Your class is fine, now you just need to make it do more One small point though. It’s conventional for custom classes to be named with an uppercase first letter, so this would be class Movie: instead of class movie: . It’s a minor thing but people will expect it, so code is easier to read when that pattern is maintained. Otherwise though, looks good, carry on!
Quercus (Quercus) April 9, 2023, 2:13pm 3 Hi @rob42 , Thanks for the class example. Following are a couple of suggestions. See Class Names in PEP 8 – Style Guide for Python Code . It suggests using the CapWords convention with class names. Accordingly, you could use Movie instead of movie . Also see object.__repr__( self ) in the Data model documentation. Based on that information, you could include this dunder method in the class Movie definition: def __repr__(self): return f'Movie("{self.title}", "{self.director}", "{self.year}")' Then print one of the Movie instances.
You should see the same code that would be used to instantiate that instance. print(movies["Monty_Python's_Life_of_Brian"]) Output: Movie("Monty Python's Life of Brian", "Terry Jones", "1979") To verify that it works, copy that output and use it to create an equivalent instance. There are of course additional features that you could add to the class Movie definition. As you learn more, just try out the ideas and enjoy the adventure. rob42 (Rob) April 9, 2023, 3:37pm 4 @Rosuav and @Quercus My thanks to you both for the feedback: it’s good to know that I am (least ways) in the right ball park.
I agree that my Class lacks functionality (which is one of the reasons for the RFC). As an example, I have implemented a function that takes a “search” argument and returns any movie in which the search term is found. The way I’ve done that, is via a string object, but I do feel that it’s a bit of a hack and that such functionality could and should be baked into my ‘Class’. I will work on that concept and post back if if needs be.
Again, thank you for your help, guidance, insights and of course your time. Peace to you both. barry-scott (Barry Scott) April 9, 2023, 4:20pm 5 The way I understand classes is that its the combination of some data and some behaviour. As suggested your Movie class could know how to play() the movie, access IMDB to return a list of actors, etc. Without the methods the class is missing that behaviour. What is the purpose of the class?
As a rule-of-thumb if your answer includes the word AND you likely have a design issue. As in Movie plays movies AND orders pizza. Rosuav (Chris Angelico) April 9, 2023, 4:37pm 6 Hang on, that actually sounds like a really good EntertainmentNight class… Kappa rob42 (Rob) April 9, 2023, 4:56pm 7 In practical terms, the purpose is a ‘moving target’, as I’m going to extend the functionality of the ‘Class’, inline with what I would like it to be able to do: it’s a very basic Class right now and simply creates instances of a movie and stores said in a dictionary object.
Keep in mind that this is a branch of off the thread that I’ve linked and I don’t want to teach the OP anything that would be considered ‘bad practice’, hence the RFC here. barry-scott (Barry Scott) April 9, 2023, 6:38pm 8 That not an issue, in fact that’s almost always the case as software envolves. You can always update the purpose as requirements change and feedback from the implementation. With OO having as clear an idea as you can of your requirements helps a lot. rob42 (Rob) April 9, 2023, 7:26pm 9 Thank you for your feedback.
I know that one can choose ignore all OO features in Python and still get quite a bit of useful coding done, which, for the most part, I have been doing over the years. I also know that there are times when OO features make a lot of sense and would actually reduce complexity, which I feel (rightly or wrongly) would be the case for the Project to which I’ve linked and from which this thread has spawned. If I’m wrong, then tell me so and I’ll advise the OP that a ‘Class’ is not the way to go and I’ll simply carry on with my exploration and exclude posting anything else to the other thread that relates to creating and using a ‘Class’ for that project: my overriding concern is that I lead the OP in the wrong direction. barry-scott (Barry Scott) April 9, 2023, 7:56pm
The rest of this page is on the live site.