02 AUG 2019

Instance variables data owned by instances of the class. This means that for each object or instance of a class, the instance variables are different. i.e. a Person class could have instance variable of name, age, etc. so each person will have a different name, age…
Magic methods in Python are the special methods which add “magic” to your class. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action. For example, when you add two numbers using the + operator, internally, the __add__() method will be called.
__str__ and __repr__:  __repr__ is a built-in function used to compute the “official” string reputation of an object, while __str__ is a built-in function that computes the “informal” string representations of an object. So both __repr__ and __str__ are used to represent objects, but in different ways. str( ) is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not. repr( ) compute the “official” string representation of an object (a representation that has all information about the abject) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object). The print ( ) statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.

More topics covered:

  • self.<property> = [value]  will create a member data on self
  • __init__ method should be used to create data members on self
  • __init__ method could accepts arguments for data member values
  • self.__<property> will create a secret data member
  • __repr__ could represent the python code of creating the object
  • _repr__could be manually called by: obj.__repr__( )
  • if __str__ and __repr__ both appear, print will call __str__
  • __str__ and __repr__ both should return a string
  • __eq__ will be called when we write: obj1== obj1
  • class name starts with Capital letter

Links:

Leave a comment