How does this “Class” | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

How does this “Class”

This was one of my challenge questions, and it’s racking my brain. What is the process it goes through to get the answer O? I need the step by step breakdown if I’m ever going to fully under stand Class methods!!! Help! https://code.sololearn.com/cm2XD05hv91j/?ref=app

22nd May 2019, 12:37 PM
Beau Tooley
Beau Tooley - avatar
3 Antworten
+ 6
This code is pretty bad. It has been made harder to read on purpose as a challenge: 1. Think of s as self. It is just a convention but an important one for the readability of the code. 2. Instantiate objects in their own line. So "in real" it would look like this (including some explanations for better understanding): https://code.sololearn.com/cUixnhw15Q0p/#py
22nd May 2019, 2:38 PM
Thoq!
Thoq! - avatar
+ 3
3*-2+3*2==0
22nd May 2019, 12:41 PM
Hubert Dudek
Hubert Dudek - avatar
+ 2
class R2vector: #creates a class called R2vector def __init__(s,x,y): #defines the initialisation method. Usually 'self' is used as the first parameter, but anything can be used. s.x = x #The x attribute of the class object (given by s.x) is set as the argument passed in the 'x' position. Similar with s.y = y. All this means that when z=R2vector(3,2) is called, an object 'z' is created where the x attribute (z.x) is set as 3 (as 3 is passed in the x-argument's position - s(elf) is ignored), and its y attribute is set as 2. def dot(a,b): return a.x*b.x+a.y*b.y This is a function defining how two of these class objects interact. It says that the two objects' x attributes get multiplied together, the two y attributes get multiplied together, and the sum of the two products is returned. In the example, two objects (one is R2vector (3,2) and the other is R2vector(-2,3)) are passed to the dot function, so their x attributes are multiplied (3*-2 = -6) and their y attributes are multiplied (2*3 = 6) and the sum of the two (-6 + 6) is 0.
22nd May 2019, 2:25 PM
Russ
Russ - avatar