Proper use of objects in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Proper use of objects in Python

# --- PYCode ---------------------- 1 : class myClass: 2 : def works_with (self): 3 : print("Hello!") 4 : 5 : def works_without(): 6 : print ("Hello!") 7 : 8 : # --- creating object --- 9 : mC = myClass() 10 : mC.works_with() # --- PYCode ---------------------- Case 1: I know that the proper way declaring objects in python is "mC = myClass()" and the above works. And if I leave everything as it is and replace the 10-th line to "mC.works_without()" it won't work. However: Case 2: If I change 9-th line to "mC = myClass" and 10-th line to "mC.works_without()" it will work. But if I change 5-th line to "def works_without(self):" and 9-th line to "mC = myClass" and 10-th line to "mC.works_without()" it won't work. So, how the objects in Python should be used and what are the differences between 2 cases above?

11th Jul 2017, 5:26 PM
Allaberdi Abdyrasulov
Allaberdi Abdyrasulov - avatar
1 Answer
+ 2
class myClass: def works_without(): print ("Hello! blank") def works_with (self): print("Hello! self") # x = myClass() creates an instance # x = myClass creates a reference to the class name # Instance syntax options for any 'self' defined method inst = myClass() inst.works_with() # option 1 myClass.works_with(inst) # option 2 # Using className options for properties with no self reference myClass.works_without() # option 3 a_reference = myClass # compare a_reference.works_with(inst) # option2 equivilent a_reference.works_without() # option3 equivilent
12th Jul 2017, 9:37 AM
richard