Making Dot function python - python

Is it possible to make a dot function that is var.function() that changes var? I realise that i can do:
class Myclass:
def function(x):
return 2
Myclass.function(1):
But i want to change it like the default python function.
def function(x):
return(3)
x=1
x.function()
print(x)
and it returns
>>> 3

class Myclass:
def __init__(self, num):
self.num = num
def function(self):
self.num += 1
def __str__(self):
return str(self.num)
x = Myclass(3)
x.function()
print(x)

This is weird usage. I suggest you to create custom class to do that, try using #property inside it if you don't want to call function in code.

Related

Changing variables for later use in Python

I'm trying to set a variable and be able to change and store that variable using set and gets. The current output is:
0
0
I'm trying to get it to be:
0
2
Can some one help me understand how to change a value and then use it later in python? Kind of like a toggle?
class Spammer:
def __init__(self, spam = 0):
self._spam = spam
# getter method
def get_spam(self):
return self._spam
# setter method
def set_spam(self, x):
if x == 1:
return self._spam+1
if x== 0:
return self._spam
spammer=Spammer()
print (spammer.get_spam())
spammer.set_spam(1)
print(spammer.get_spam())
There is an #property decorator builtin so you could do the following:
class Spammer:
def __init__(self, spam = 0):
self._spam = spam
#property
def spam(self):
return self._spam
#spam.setter
def spam(self, new_spam):
self._spam = new_spam

Using a method both inside a class and outside - python

So I have a function that, so far, I have had as a method inside a class. Turns out now I want to use it without making an instance of the class.
What is the best way of doing this without having to massively change the code?
Example codes follow:
Before:
class A(object):
def method1(self, input):
return input*3 + 7
def method2(self, input):
return self.method1(input) + 4
Basically I want to take method1 out of the class so that i can use it without making an instance of A, but also do not want change self.method1 to method1 everywhere.
My idea:
def method1(input):
return input*3 + 7
class A(object):
def __init__(self):
self.method1 = method1
def method2(self, input):
return self.method1(input) + 4
--
Is this bad practice? How else could one call a method from inside a class? Or alternatively how can a class incorporate methods methods outside it?
Try this:
def method1(input):
return input*3 + 7
class A(object):
def method1(self, input):
return method1(input)
def method2(self, input):
return self.method1(input) + 4
this should work
It won't work because of the self parameter. Instead, define it like this:
class A(object):
def method1(self, input):
return method1(input)
This is called a static method in order to do this, your function can not contain (self)
class A(object):
def method_one(variable):
return variable * 3 + 7
def method_two(self, variable):
return self.method_one(variable) + 4
print(A.method_one(10))
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 method_out.py
37
Turn into a staticmethod the method you don't need or don't want an instance of its class.
The ideia would be like the following:
>>> class A:
#staticmethod
def m(value):
return value*3+7
def sum(self, value):
return self.m(value) + 4
>>> a = A()
>>> a.sum(4)
23
>>> 4+A.m(4)
23
>>>
Notice the difference from a normal method to the static one. On the static one you ommit the self parameter, thus meaning you don't need an instance of its class to use that static method.

python; how to pass one argument through multiple methods in a class

I am learning about class structure in python. Would like to know if it's possible to pass one argument through more than one method.
class Example(object):
def __init__(self, x):
self.x = x
def square(self):
return self.x**2
def cube(self):
return self.x**3
def squarethencube(y):
sq = Example.square(y)
cu = Example.cube(sq)
return cu
two = Example(2)
print(two.squarethencube())
Error is on line 10; AttributeError: 'int' object has no attribute 'x'
The goal is to use the 'squarethencube' method to pass '2' to square(), which is 4. Then pass '4' to cube(). The desired output is '64'. Obviously, you can write a function to do the math in a very simple way; the question here is how to use multiple methods.
I understand the error in that .x is getting assigned as an attribute onto the output of cube(sq). I was getting the same error, but on line 7, before I changed the argument to y (from self.x).
I've found some similar answers here but I need a simpler explanation.
Currently, square and cube are methods bound to the class; however, you are accessing them in squarethencube by class name, but they are methods, and thus rely on a reference to the class from an instance. Therefore, you can either create two new instances of the class or use classmethod:
Option1:
class Example(object):
def __init__(self, x):
self.x = x
def square(self):
return self.x**2
def cube(self):
return self.x**3
def squarethencube(self, y):
sq = Example(y).square()
cu = Example(y).cube()
return cu
Option 2: use a classmethod:
class Example(object):
def __init__(self, x):
self.x = x
#classmethod
def square(cls, x):
return x**2
#classmethod
def cube(cls, x):
return x**3
def squarethencube(self, y):
sq = Example.square(y)
cu = Example.cube(sq)
return cu
class Example:
def __init__(self, x):
self.x = x
def square(self):
return self.x**2
def cube(self):
return self.x**3
def squarethencube(self):
return (self.x**2)**3
two = Example(2)
print(two.squarethencube())

How do I return the definition of a class in python?

Say I have a class "NumberStore"
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
And later on, for the purpose of serialization, I want to print a definition of the class, either exactly as stated, or equivalently stated. Is there any way in python to access a class's definition as in the idealized example below?
>>> NumberStore.print_class_definition()
"class NumberStore(object):\n def __init__(self, num):\n self.num = num\n \n def get(self):\n return self.num"
Yep, with inspect.getsource:
from inspect import getsource
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
#classmethod
def print_class_definition(cls):
return getsource(cls)
Use inspect.getsource.
import inspect
source_text = inspect.getsource(NumberStore)

how to make an operator function in python?

I need to make an operators to an object and I wonder what is the best way.
for example for the operator add
can I write this in this way?
def _add_(self,other):
new=self.add(self,other)// can I write like that?
return new
thanks for the help!
You would use the python magic function __add__ to take care of the +:
Example:
class A():
def __init__(self, num):
self.num = num
def __add__(self, other):
return self.num + other
a = A(6)
>>> print a+5
11
For greater flexibility, you should also define __radd__, this is for the reverse addition case 5+a which would not work in the example above.
class A():
def __init__(self, num):
self.num = num
def __add__(self, other):
return self.num + other
def __radd__(self, other):
return self.num + other
>>> a = A(6)
>>> print 5+a
11
>>> print a+5
11
Or if you want to return as an object instead of an int, you can do it as:
class A():
def __init__(self, num):
self.num = num
def __add__(self, other):
return A(self.num + other)
a = A(5)
b = a+5
print b.num
10
print a.num
5
What has been demonstrated above is operator overloading. It overrides the built-in default methods for handling operators by letting the user define custom methods for the operators.
Here is a list you might find useful as to which operators can be overloaded

Categories