Classes and methods
object-oriented language: A language that provides features, such as user defined classes and inheritance, that facilitate object-oriented programming.
object-oriented programming: A style of programming in which data and the operations that manipulate it are organized into classes and methods.
method: A function that is defined inside a class definition and is invoked on instances of that class.
override: To replace a default. Examples include replacing a default value with a particular argument and replacing a default method by providing a new method with the same name.
initialization method: A special method that is invoked automatically when a new object is created and that initializes the object’s attributes.
operator overloading: Extending built-in operators (+, -, *, >, >, etc.) so that they work with user-defined types.
dot product: An operation defined in linear algebra that multiplies two Points and yields a numeric value.
scalar multiplication: An operation defined in linear algebra that multiplies each of the coordinates of a Point by a numeric value.
polymorphic: A function that can operate on more than one type. If all the operations in a function can be applied to a type, then the function can be applied to a type.
Sample Example of a Class
>>> class game(): name = '30 seconds race' def start_race(self): time.sleep(30) print 'Time up!!' >>> test = game() >>> test.name '30 seconds race' >>> test.start_race() Time up!!
Sample Example of a Class(part 2)
class Point: def __init__(self, x=0, y=0): # initialisation method self.x = x self.y = y def __str__(self): # output for print function on this class return '(%s, %s)' % (self.x, self.y) >>> p = Point(3, 4) >>> print p (3, 4)
Sample Example of a Class “operator overloading”(part 2)
class Point: # previously defined methods here... def __add__(self, other): return Point(self.x + other.x, self.y + other.y) >>> p1 = Point(3, 4) >>> p2 = Point(5, 7) >>> p3 = p1 + p2 >>> print p3 (8, 11)
Classes multiplication – magic functions
def __mul__(self, other): return self.x * other.x + self.y * other.y >>> p1 * p1 (9, 16)
Class & Scalar multiplication
def __mul__(self, other): return self.x * other.x + self.y * other.y >>> p1 * 10 (30, 40)
How to compare two classes?
To compare the contents of the objects—”deep equality”—we can write a function to check if both are same class and has same attributes
How to check if two variables are point to same information?
we can ‘is’ for checking if two variable/objects are representing same.
>>> class car(): pass >>> a = car() >>> b = car() >>> a = b # assigning 'b' to 'a' >>> a is b True >>> a == b True >>> a = car() >>> b = car() >>> a is b False >>> a == b False >>>
How to copy two objects?
Default pkg – copy has
– copy function which does as following
- deep_copy function which we can use for copying(two diff. objs but same* parameter)
>>> import copy >>> a = car() >>> b = car() >>> a = copy.copy(b) >>> a is b False >>> a == b False
##########################################################################################################################################################
All the example here may be or may not be connected to each other depending on the need. Be wise & understand where & how you can use this functionality for your need.
Getter and Setter Method
class Square:
def __init__(self, height=0, width=0):
self.height = height
self.width = weigth
# getter
@property
def height(self):
print(“retriving the height”)
return self.__height
# setter
@height.setter
def height(self, value):
if value.isdigit():
self.__height = value
else:
print(‘InputError: only numerical value pace’)
Note: Check the setter and getter method added for Square class
- Actual value if
height
is stored in another variable called__height
- Keyword
@property
for getter method - Keyword
#.setter
for setter method
Methods – class methods
@staticmethod
def whoami():
print(“awesome”)
Class Methods: It does not matter if class is initialised, it just works.
Note:
- keyword to note is
staticmethod
- Inside params there is no
self
Magic Method
def __str__(self):
return “know thyself”, self.__name__, self.health, self.hp
Note: This method gives a meaning result when you print this object otherwise you will only see an instance’s meta data which you won’t understand.
Inheritance
class Mammal(Animal):
def __init__(self, birthType=”born alive”,…):
Animal.__init(self, birthType, appearance,…._:
self.__new_features = new_feature
@property
def new_features():
return self.__nurseYoung
@new_feature.setter
def nurseYoung(self, nurseYpung):
if nurseYoung.isalpha():
self.__nurseYOung = nurseYOung
else:
print “nurseYOung has to be a string”
Note: Look at is init method
- We used parentheses in the Class Name as we using inheritance – otherwise not required.
- This class called its parent class Animal & then does the initialisation using Animal’s init and then
- For extra variables added variable with its custom getter & setter methods
overriding
def __str__(self):
## appending super’s output & printing a new info
return super().__str__() + “ and also nurse their young”
Note: This method is to call its parent & use its out and then makes its own new with added information.
- Parent already has that method.
Function Overload / Operator Overload ==> no. of input variables is not fixed
# In Python - type casting setting is Dynamic
# In Java, C - its static Type Casting
## def sumAll(self, a_int, b_int, c_int)
## def sumAll(self, a_int, b_int, c_str)
## def sumAll(self, a_int, b_str, c_str)
def sumAll(self, *args):
sum = 0
for i in args:
sum += int(i)
return sum
Note: This method works for any number of inputs number* whether given as number or strings
polymorphism
def tell_me_whp_are_you(object):
print(‘my name is’, object.__name__)
Note: This method works for any object/instance that has name attribute, it does not matter what kind of object it is.
Magic method (part2) (Already shown once above for str)
def __add__(vector1, vector2):
vector1.x += vector2.x
vector1.y += vector2.y
vector1.z += vector2.z
vector2 = vector1 # repoint & del vector2
return vector1
Note: Like init, this add can help you create basic functions like add, sub, multiplayer, div, mod-modulus.
- [Classes, Variables/Attributes, Function/Methods, Getter/Property, Setter] (https://www.youtube.com/watch?v=1AGyBuVCTeE)
- [Inheritance, Magic Function, Overriding, Function Overloading, polymorphism, magic methods] (https://www.youtube.com/watch?v=d8kCdLCi6Lk)
Yea sure!! You may email at sam1990kumar@gmail.com
LikeLike