Python Tutorial
#!/usr/bin/python class Arthmetic: def __init__(self, a, b): self.a = a; self.b = b; def get_subtraction(self): print("sub of %d and %d is: %d" % (self.a, self.b, (self.a-self.b))); arth = Arthmetic(10, 3); arth.get_subtraction();Output:
$ python test_instance_method.py sub of 10 and 3 is: 7
#!/usr/bin/python class Arithmetic: def __init__(self, a, b): self.a = a; self.b = b; @staticmethod def get_sum(a, b): print("sum of %d and %d is: %d" %(a, b, a+b)); # static method is called using class name Arithmetic.get_sum(10, 3); arth = Arithmetic(10, 3); # static method is called using instance. arth.get_sum(34, 2);Output:
$ python test_static_method.py sum of 10 and 3 is: 13 sum of 34 and 2 is: 36
#!/usr/bin/python class Arithmetic: def __init__(self, a, b): self.a = a; self.b = b; @classmethod def get_sum(cls, a, b): print("%s - sum of %d and %d is: %d" %(cls, a, b, a+b)); Arithmetic.get_sum(10, 3); arth = Arithmetic(10, 3); arth.get_sum(34, 2);Output:
$ python test_static_method.py __main__.Arithmetic - sum of 10 and 3 is: 13 __main__.Arithmetic - sum of 34 and 2 is: 36
#!/usr/bin/python class Arithmetic: def __init__(self, a, b): self.a = a; self.b = b; @classmethod def get_sum(cls, a, b): print("%s - sum of %d and %d is: %d" %(cls, a, b, a+b)); class TestClass(Arithmetic): def __init__(self, a, b): Arithmetic.__init__(self, a, b); pass; TestClass.get_sum(10, 3); arth = TestClass(12, 2); arth.get_sum(34, 2);Output:
$ python test_static_method.py __main__.TestClass - sum of 10 and 3 is: 13 __main__.TestClass - sum of 34 and 2 is: 36
#!/usr/bin/python class Arthmetic: def __init__(self, a, b): self.a = a; self.b = b; def get_subtraction(self): print("sub of %d and %d is: %d" % (self.a, self.b, (self.a-self.b))); # class method returns class instance with initialized values for a and b @classmethod def initialize_a_b(cls, a, b): return cls(a, b); # static method to compute sum of a and b @staticmethod def get_sum(a, b): print("sum of %d and %d is: %d" %(a, b, a+b)); arth1 = Arthmetic(10, 3); # invokes instance method arth1.get_subtraction(); # invokes class method arth2 = Arthmetic.initialize_a_b(14, 5); print("arth1 instance a: %d and b: %d" % (arth1.a, arth1.b)); print("arth2 instance a: %d and b: %d" % (arth2.a, arth2.b)); # invokes static methods. Arthmetic.get_sum(12, 5); arth2.get_sum(13, 2); ~Output:
$ python test_static_method.py sub of 10 and 3 is: 7 arth1 instance a: 10 and b: 3 arth2 instance a: 14 and b: 5 sum of 12 and 5 is: 17 sum of 13 and 2 is: 15
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page