Builtin attributes of a class :
- For each and every class in python some attributes/properties are going to be added automatically by the python interpreter.
- the attributes which are added by the python interpreter are known as builtin attributes/properties.
_ _dict_ _
_ _doc_ _
_ _name_ _
_ _module_ _
_ _bases_ _
_ _weakref_ _
class Test:
"""sample class for builtin attributes"""
a=100
def m1(self):
print("in m1 of test")
print(Test.a)
t1=Test()
t1.m1()
print(Test.__doc__)
print(Test.__dict__)
print(Test.__name__)
print(Test.__module__)
print(Test.__bases__)
print(Test.__weakref__)
100
in m1 of test
sample class for builtin attributes
{'m1': <function Test.m1 at 0x0000000000761400>, 'a': 100, '__doc__': 'sample class for builtin attributes', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__dict__': <attribute '__dict__' of 'Test' objects>}
Test
__main__
(<class 'object'>,)
<attribute '__weakref__' of 'Test' objects>
- It is possible to define two kinds of methods with-in a class that can be called without an instance.
Class Method:
- A class method takes cls as first parameter.
- A class method can access or modify class state.
- We use @classmethod decorator in python to create a class method.
- We generally use class method to create factory methods.
Syntax:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
........................
........................
........................
Static Method:
- A static method needs no specific parameters.
- A static method can’t access or modify it.
- We use @staticmethod decorator to create a static method in python.
- We generally use static methods to create utility functions.
Syntax:
class C(object):
@staticmethod
def fun( arg1, arg2, ...):
....................
....................
....................
Example:
class Test(object):
x=20
def m1(self):
print"hai,i am in instance method"
print(Test.x)
@classmethod
def m2(cls):
print "hai,i am in class method"
print(Test.x)
@staticmethod
def m3():
print "hai,i am in static method"
print(Test.x)
Test.m2()
Test.m3()
Test.m1()
No comments:
Post a Comment