Three different Method calls of Python class - python

I am reading this article. In this article a line says :
For a Class C, an instance x of C and a method m of C the following
three method calls are equivalent:
type(x).m(x, ...)
C.m(x, ...)
x.m(...)
I tried to convert this statement into program like this :
class C:
def __init__(self,a,c):
self.a=a
self.b=c
def m(self):
d=self.a+self.b
x=C(1,2)
x.m()
print(type(x).m(x))
print(C.m(x))
print(x.m())
But i am getting no clue what these three methods meant and how they are working ?? If my program is using method wrong then please correct it.
edit
I am not asking for modifications for this code , I am asking how those three methods are used and provide one example with each method calls.
If you can provide proper example for each three method that would be very helpful for me.

If using python 2.7, you should derive C from object in order to get the correct type with type(x), which knows the method m.
class C(object):
def __init__(self,a,c):
self.a=a
self.b=c
def m(self):
return self.a+self.b
x=C(1,2)
x.m()
print(type(x).m(x))
print(C.m(x))
print(x.m())
I think in python 3, this is implicit. And yes, instead of calculating d, I just return the result - so you see something.
Edit regarding your clarification:
The three ways to call the method are shown for illustration. I would not see any obvious reason for not using x.m() if possible. But in python, that is a shortcut for: Call the method m of the type of x on the instance x.
The type(x).m(x) is the most literal way to write what is going on. Now, type(x) is C (in python 3 or with new-style classes - derived from object - at least, else instance), so the first and second way of writing are equivalent as well.

Your m isn't returning anything.
You want
def m(self):
return self.a + self.b
Most likely within your C class

Related

Should I use python magic methods directly?

I heard from one guy that you should not use magic methods directly. and I think in some use cases I would have to use magic methods directly. So experienced devs, should I use python magic methods directly?
I intended to show some benefits of not using magic methods directly:
1- Readability:
Using built-in functions like len() is much more readable than its relevant magic/special method __len__(). Imagine a source code full of only magic methods instead of built-in function... thousands of underscores...
2- Comparison operators:
class C:
def __lt__(self, other):
print('__lt__ called')
class D:
pass
c = C()
d = D()
d > c
d.__gt__(c)
I haven't implemented __gt__ for neither of those classes, but in d > c when Python sees that class D doesn't have __gt__, it checks to see if class C implements __lt__. It does, so we get '__lt__ called' in output which isn't the case with d.__gt__(c).
3- Extra checks:
class C:
def __len__(self):
return 'boo'
obj = C()
print(obj.__len__()) # fine
print(len(obj)) # error
or:
class C:
def __str__(self):
return 10
obj = C()
print(obj.__str__()) # fine
print(str(obj)) # error
As you see, when Python calls that magic methods implicitly, it does some extra checks as well.
4- This is the least important but using let's say len() on built-in data types such as str gives a little bit of speed as compared to __len__():
from timeit import timeit
string = 'abcdefghijklmn'
print(timeit("len(string)", globals=globals(), number=10_000_000))
print(timeit("string.__len__()", globals=globals(), number=10_000_000))
output:
0.5442426
0.8312854999999999
It's because of the lookup process(__len__ in the namespace), If you create a bound method before timing, it's gonna be faster.
bound_method = string.__len__
print(timeit("bound_method()", globals=globals(), number=10_000_000))
I'm not a senior developer, but my experience says that you shouldn't call magic methods directly.
Magic methods should be used to override a behavior on your object. For example, if you want to define how does your object is built, you override __init__. Afterwards when you want to initialize it, you use MyNewObject() instead of MyNewObject.__init__().
For me, I tend to appreciate the answer given by Alex Martelli here:
When you see a call to the len built-in, you're sure that, if the program continues after that rather than raising an exception, the call has returned an integer, non-negative, and less than 2**31 -- when you see a call to xxx.__len__(), you have no certainty (except that the code's author is either unfamiliar with Python or up to no good;-).
If you want to know more about Python's magic methods, I strongly recommend taking a look on this documentation made by Rafe Kettler: https://rszalski.github.io/magicmethods/
No you shouldn't.
it's ok to be used in quick code problems like in hackerrank but not in production code. when I asked this question I used them as first class functions. what I mean is, I used xlen = x.__mod__ instead of xlen = lamda y: x % y which was more convenient. it's ok to use these kinda snippets in simple programs but not in any other case.

What is the proper way to access python class variables?

Having a class
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
Both methods (Func1 and Func2) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address z.
The result of Func* would only differ if an instance would shadow z with something like self.z = None.
What is the proper python way to access the class variable z using the syntax of Func1 or Func2?
I would say that the proper way to get access to the variable is simply:
a_instance.z #instance variable 'z'
A.z #class variable 'z'
No need for Func1 and Func2 here.
As a side note, if you must write Func2, it seems like a classmethod might be appropriate:
#classmethod
def Func2(cls):
return cls.z
As a final note, which version you use within methods (self.z vs. A.z vs. cls.z with classmethod) really depends on how you want your API to behave. Do you want the user to be able to shadow A.z by setting an instance attribute z? If so, then use self.z. If you don't want that shadowing, you can use A.z. Does the method need self? If not, then it's probably a classmethod, etc.
I would usually use self.z, because in case there are subclasses with different values for z it will choose the "right" one. The only reason not to do that is if you know you will always want the A version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creating of mixin classes.
If you don't care about value clobbering and things like that, you're fine with self.z. Otherwise, A.z will undoubtedly evaluate to the class variable. Beware, though, about what would happen if a subclass B redefines z but not Func2:
class B(A):
z = 7
b = B()
b.Func2() # Returns 0, not 7
Which is quite logical, after all. So, if you want to access a class variable in a, somehow, polymorphic way, you can just do one of the following:
self.__class__.z
type(self).z
According to the documentation, the second form does not work with old-style classes, so the first form is usually more comptaible across Python 2.x versions. However, the second form is the safest one for new-style classes and, thus, for Python 3.x, as classes may redefine the __class__ attribute.

How do I dynamically create a function with the same signature as another function?

I'm busy creating a metaclass that replaces a stub function on a class with a new one with a proper implementation. The original function could use any signature. My problem is that I can't figure out how to create a new function with the same signature as the old one. How would I do this?
Update
This has nothing to do with the actual question which is "How do I dynamically create a function with the same signature as another function?" but I'm adding this to show why I can't use subclasses.
I'm trying to implement something like Scala Case Classes in Python. (Not the pattern matching aspect just the automatically generated properties, eq, hash and str methods.)
I want something like this:
>>> class MyCaseClass():
... __metaclass__ = CaseMetaClass
... def __init__(self, a, b):
... pass
>>> instance = MyCaseClass(1, 'x')
>>> instance.a
1
>>> instance.b
'x'
>>> str(instance)
MyCaseClass(1, 'x')
As far as I can see, there is no way to that with subclasses.
I believe functools.wraps does not reproduce the original call signature. However, Michele Simionato's decorator module does:
import decorator
class FooType(type):
def __init__(cls,name,bases,clsdict):
#decorator.decorator
def modify_stub(func, *args,**kw):
return func(*args,**kw)+' + new'
setattr(cls,'stub',modify_stub(clsdict['stub']))
class Foo(object):
__metaclass__=FooType
def stub(self,a,b,c):
return 'original'
foo=Foo()
help(foo.stub)
# Help on method stub in module __main__:
# stub(self, a, b, c) method of __main__.Foo instance
print(foo.stub(1,2,3))
# original + new
use functools.wraps
>>> from functools import wraps
>>> def f(a,b):
return a+b
>>> #wraps(f)
def f2(*args):
print(args)
return f(*args)
>>> f2(2,5)
(2, 5)
7
It is possible to do this, using inspect.getargspecs. There's even a PEP in place to make it easier.
BUT -- this is not a good thing to do. Can you imagine how much of a debugging/maintenance nightmare it would be to have your functions dynamically created at runtime -- and not only that, but done so by a metaclass?! I don't understand why you have to replace the stub dynamically; can't you just change the code when you want to change the function? I mean, suppose you have a class
class Spam( object ):
def ham( self, a, b ):
return NotImplemented
Since you don't know what it's meant to do, the metaclass can't actually implement any functionality. If you knew what ham were meant to do, you could do it in ham or one of its parent classes, instead of returning NotImplemented.

Setting a lambda function as a property

Consider these two classes:
class Test(int):
difference = property(lambda self: self.__sub__)
class Test2(int):
difference=lambda self: self.__sub__
Is there any difference between these two classes? New: If so, what is the purpose of using the property to store a lambda function that returns another function?
Update: Changed the question to what I should have asked in the first place. Sorry. Even though I can now know the solution from the answers, it would be unfair for me to do a self answer in these circumstances. (without leaving the answer for a few days at least).
Update 2: Sorry, I wasn't clear enough again. The question was about the particular construction, not properties in general.
For Test1, you could use .difference - for Test2, you'd need to use .difference() instead.
As for why you might use it, a potential use would be to replace something that was previously directly stored as a property with a dynamic calculation instead.
For instance, if you used to store property obj.a, but then you expanded your implementation so that it knew instead properties obj.b and obj.c that could be used to calculate a, but could also be used to calculate different things. If you still wanted to provide backwards-compat with things that used the previous object form, you could implement obj.a as a property() that calculated a based on b and c and it'd behave to those older code fragments as it previously did, with no other code modification needed.
Edit: Ah, I see. You are asking why anybody would do exactly the code above. It's not, in fact a question about why to make a lambda or a property at all, it's not a question of the differences between the two examples, and not even why you want to make a property out of a lambda.
Your question is "Why would anybody make a property of a lambda that just returns self.__sub__".
And the answer is: One wouldn't.
Let's assume somebody wants to do this:
>>> foo = MyInt(8)
>>> print foo.difference(7)
1
So he tries to accomplish it by this class:
class MyInt(int):
def difference(self, i):
return self - i
But that's two lines, and since he is a Ruby programmer and believes that good code is code that has few lines of code, he changes it to:
class MyInt(int):
difference = int.__sub__
To save one line of code. But apparently, things are still too easy. He learned in Ruby that a problem is not properly solved unless you use anonymous code blocks, so he will try to use Pythons nearest equivalent, lambdas, for absolutely no reason:
class MyInt(int):
difference=lambda self, i: self - i
All these works. But things are still WAY to uncomplicated, so instead he decides to make things more complex, by not doing the calculation, but returning the sub method:
class MyInt(int):
difference=lambda self: self.__sub__
Ah, but that doesn't work, because he needs to call difference to get the sub-method:
>>> foo = MyInt(8)
>>> print foo.difference()(7)
1
So he makes it a property:
class MyInt(int):
difference=property(lambda self: self.__sub__)
There. Now he has found the maximum complexity to solve a non-problem.
But normal people wouldn't do any of these, but do:
>>> foo = 8
>>> print foo - 7
1
People have given there opinion without analyzing it, it can be better solved by python itself, below is the code to check the difference
import difflib
from pprint import pprint
s1 = """
class Test(int):
difference=property(lambda self: self.__sub__)
"""
s2 = """
class Test(int):
difference=lambda self: self.__sub__
"""
d = difflib.Differ()
print "and the difference is..."
for c in d.compare(s1, s2):
if c[0] in '+-': print c[1:],
and as expected it says
and the difference is...
p r o p e r t y ( )
Yes, in one case difference is a property. If you are asking what a property is, you can see it as a method that gets automatically called.
Yes, in one case difference is a property
Purpose of property can be
1.
To provide get/set hooks while accessing an attribute
e.g. if you used to have class with attribute a, later on you want to do something else when it is set, you can convert that attribute to property without affecting the interface or how users use your class. So in the example below class A and B are exactly same for a user but internally in B you can do many things in get/setX
class A(object):
def __init__(self):
self.x = 0
a = A()
a.x = 1
class B(object):
def __init__(self):
self.x = 0
def getX(self): return self._x
def setX(self, x): self._x = x
x = property(getX, setX)
b = B()
B.x = 1
2.
As implied in 1, property is a better alternative to get/set calls, so instead of getX, setX user uses less verbose self.x and self.x = 1, though personally I never make a property just for getting or setting a attribute, if need arises it can be done later on as shown in #1/
as far as difference in concerned, property provide you with get/set/del for an atribute, but in the example you have given a method(lambda or proper function) can only be used to do one of get/set or del, so you will need three such lambdas differenceSet, differenceGet, differenceDel

Is it bad form to call a classmethod as a method from an instance?

Ex.
If I have something like this:
class C(object):
#classmethod
def f(cls, x):
return x + x
This will work:
c = C()
c.f(2)
4
But is that bad form?
Should I only call
C.f()
or
c.__class__.f()
Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.
?
If you are tempted to call a class method from an instance you probably don't need a class method.
In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction).
class C(object):
#staticmethod
def f(x):
return x + x
this way it's "good form" to do both
c = C()
c.f(2)
and
C.f(2)
I don't recall using a classmethod like this from outside the class, but it is certainly ok for an instance method to call a classmethod on itself (e.g. self.foo() where foo is a classmethod). This makes sure that inheritance acts as expected, and will call .foo() in the right subclass instead of the base class.
It's mainly just confusing looking. If I were using your class and saw this, it would make me wonder what other surprises are in there, it just looks like bad design.
Is there a reason it's not just a staticmethod?
C.f() is clearer than c_instance.f(), and c_instance.__class__.f() is just ugly. Since clarity and beauty are dearly loved characteristics in the python community, I'd tend to say that C.f() is the best route.
Is there any particular reason you even want to call it in either of the other ways?
If you have an instance of C already, why do you need f() to be a class method? Not only is it bad form, its usually not necessary. Someone on the net says: "This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case."
Although, page 484 of learning python notes that you can call the method either way and it will be exactly the same as long as you pass the same instance in.
I came across this where I was calling some classmethods (that need to be classmethods so that I still have reference to the class) from a non-classmethod, like the following.
class A:
def a(self, number):
print("a", self, number)
self.b(number)
#classmethod
def b(cls, number):
print("b", cls, number + 1)
cls.c(number)
#classmethod
def c(cls, number):
print("c", cls, number * 2)
b = A()
b.a(3)
The above code produces the following result:
a <__main__.A object at 0x000001FAC09FE358> 3
b <class '__main__.A'> 4
c <class '__main__.A'> 6
I'm not saying that it's the best convention, but it doesn't break anything in Python 3.6

Categories