Classes and Objects
camelCase
PascalCase
class PascalCase # always
object = class() to declare a object part of class and then perform functions
memory is alloted only after the above step
class ClassName:
class_attribute1=value1
attribute2=value2
object = ClassName()
object_attribute= value # updates individual value or add new value
object_attribute > class_attribule # more powerful(in times of calling them)
self-> gets automatically replaced with object name # to use within a func in class self.variable
object.fun()==class.fun(object) **
@staticmethod # written before def to make it as class.fun() # it is a decorator
def __init__(self, {can contain more variable})==it gets automatically run even without calling when a object is created.
eg. def __init__(self,a,b):
self.a=a
self.b=b
object=class(5,80)
the above is called a constructor and its arguments are written in object=class(arguments)
__method__ are called dunder method
types of function_names in a class:
attribute # normal
_attribute # normal used for human debugging
__attribute # saved as _classname__attribute()
dir(object) to check attributes
__name__ by default is equal to" __main__" or the name of module used
self.attribute use only if defined in __init__ method else directly call variable.
object.variable == instance , class.variable
print(object.__dict__) shoes all instance attributes
@classmethod- def function(cls): cls.variable
anything can be written instead of self
creating a new object by function # class method as alternate constructor (like __init__)
@classmethod
def new_object(cls,string):
name,salary=string.split("-")
return cls(name,salary)
help(ClassName)==show details
print(function)==output is return value of function
__repr__ direct calling eg print(variable)==print(repr(variable))
@property
def email(self):
return self.name+"@gmail.com"
@email.setter
def email(self,given_email):
# self.email=given_email show error as we can't directly change
self.name=given_email.split('@')[0]
@function_name.deleter
def function_name(self):
del self.attribute1
self.attribute2=None
use with if condition if ==none in .setter
del object.function_name [which was used as property]
from abc import ABCMeta or ABC(for py 3.4 or higher), abstractmethod
@abstractmethod
class BaseClassName(metaclass=ABCMeta)/(ABC)
@abstractmethod
def function_name():
it makes sure that any child class derived from the base class need to have a function which is specified in base class.
Comments
Post a Comment
For any queries or suggestions
Comment Here