Communicating between objects in Python - python

I have something like this:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
print exampleClass.doSomething(5)
exampleClass2.callDefDoSomething()
-
TypeError: unbound method callDefDoSomething() must be called
with exampleClass2 instance as first argument (got nothing instead)
I started to learn about objects in Python but i cant find solution for this :(

You need to create an instance of the class, i.e., an active object, to make things work:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def __init__(self):
self.member1 = exampleClass()
def callDefDoSomething(self):
print self.member1.doSomething(5)
object2 = exampleClass2()
object2.callDefDoSomething()

doSomething is a method of exampleClass. Therefore, it has to be called for an instance of this class.
In callDefDoSomething, you use
exampleClass.doSomething(5)
exampleClass, however, is not an instance of this class but the class itself. What you want to use here is
self.doSomething(5)
self refers to the instance of exampleClass2, for whichcallDefDoSomethingsis invoked, which, due to inheritance, is an instance ofexampleClass`.

Regular class methods can only be called for instances not for classes. So if you want to call callDefDoSomething you have to first instantiate exampleClass2. You also have to instantiate exampleClass inside the call to callDefDoSomething.
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
exampleClassInstance = exampleClass()
print exampleClassInstance.doSomething(5)
exampleClass2Instance = exampleClass2()
exampleClass2Instance.callDefDoSomething()
If you want to call methods on classes you should try classmethods. Check the documentation on classes in the python tutorial.

You can use this:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
print super(exampleClass2,self).doSomething(5)
example = exampleClass2()
example.callDefDoSomething()

Related

How to overwrite self after reading yaml? [duplicate]

I would like to replace an object instance by another instance inside a method like this:
class A:
def method1(self):
self = func(self)
The object is retrieved from a database.
It is unlikely that replacing the 'self' variable will accomplish whatever you're trying to do, that couldn't just be accomplished by storing the result of func(self) in a different variable. 'self' is effectively a local variable only defined for the duration of the method call, used to pass in the instance of the class which is being operated upon. Replacing self will not actually replace references to the original instance of the class held by other objects, nor will it create a lasting reference to the new instance which was assigned to it.
As far as I understand, If you are trying to replace the current object with another object of same type (assuming func won't change the object type) from an member function. I think this will achieve that:
class A:
def method1(self):
newObj = func(self)
self.__dict__.update(newObj.__dict__)
It is not a direct answer to the question, but in the posts below there's a solution for what amirouche tried to do:
Python object conversion
Can I dynamically convert an instance of one class to another?
And here's working code sample (Python 3.2.5).
class Men:
def __init__(self, name):
self.name = name
def who_are_you(self):
print("I'm a men! My name is " + self.name)
def cast_to(self, sex, name):
self.__class__ = sex
self.name = name
def method_unique_to_men(self):
print('I made The Matrix')
class Women:
def __init__(self, name):
self.name = name
def who_are_you(self):
print("I'm a women! My name is " + self.name)
def cast_to(self, sex, name):
self.__class__ = sex
self.name = name
def method_unique_to_women(self):
print('I made Cloud Atlas')
men = Men('Larry')
men.who_are_you()
#>>> I'm a men! My name is Larry
men.method_unique_to_men()
#>>> I made The Matrix
men.cast_to(Women, 'Lana')
men.who_are_you()
#>>> I'm a women! My name is Lana
men.method_unique_to_women()
#>>> I made Cloud Atlas
Note the self.__class__ and not self.__class__.__name__. I.e. this technique not only replaces class name, but actually converts an instance of a class (at least both of them have same id()). Also, 1) I don't know whether it is "safe to replace a self object by another object of the same type in [an object own] method"; 2) it works with different types of objects, not only with ones that are of the same type; 3) it works not exactly like amirouche wanted: you can't init class like Class(args), only Class() (I'm not a pro and can't answer why it's like this).
Yes, all that will happen is that you won't be able to reference the current instance of your class A (unless you set another variable to self before you change it.) I wouldn't recommend it though, it makes for less readable code.
Note that you're only changing a variable, just like any other. Doing self = 123 is the same as doing abc = 123. self is only a reference to the current instance within the method. You can't change your instance by setting self.
What func(self) should do is to change the variables of your instance:
def func(obj):
obj.var_a = 123
obj.var_b = 'abc'
Then do this:
class A:
def method1(self):
func(self) # No need to assign self here
In many cases, a good way to achieve what you want is to call __init__ again. For example:
class MyList(list):
def trim(self,n):
self.__init__(self[:-n])
x = MyList([1,2,3,4])
x.trim(2)
assert type(x) == MyList
assert x == [1,2]
Note that this comes with a few assumptions such as the all that you want to change about the object being set in __init__. Also beware that this could cause problems with inheriting classes that redefine __init__ in an incompatible manner.
Yes, there is nothing wrong with this. Haters gonna hate. (Looking at you Pycharm with your in most cases imaginable, there's no point in such reassignment and it indicates an error).
A situation where you could do this is:
some_method(self, ...):
...
if(some_condition):
self = self.some_other_method()
...
return ...
Sure, you could start the method body by reassigning self to some other variable, but if you wouldn't normally do that with other parametres, why do it with self?
One can use the self assignment in a method, to change the class of instance to a derived class.
Of course one could assign it to a new object, but then the use of the new object ripples through the rest of code in the method. Reassiging it to self, leaves the rest of the method untouched.
class aclass:
def methodA(self):
...
if condition:
self = replace_by_derived(self)
# self is now referencing to an instance of a derived class
# with probably the same values for its data attributes
# all code here remains untouched
...
self.methodB() # calls the methodB of derivedclass is condition is True
...
def methodB(self):
# methodB of class aclass
...
class derivedclass(aclass):
def methodB(self):
#methodB of class derivedclass
...
But apart from such a special use case, I don't see any advantages to replace self.
You can make the instance a singleton element of the class
and mark the methods with #classmethod.
from enum import IntEnum
from collections import namedtuple
class kind(IntEnum):
circle = 1
square = 2
def attr(y): return [getattr(y, x) for x in 'k l b u r'.split()]
class Shape(namedtuple('Shape', 'k,l,b,u,r')):
self = None
#classmethod
def __repr__(cls):
return "<Shape({},{},{},{},{}) object at {}>".format(
*(attr(cls.self)+[id(cls.self)]))
#classmethod
def transform(cls, func):
cls.self = cls.self._replace(**func(cls.self))
Shape.self = Shape(k=1, l=2, b=3, u=4, r=5)
s = Shape.self
def nextkind(self):
return {'k': self.k+1}
print(repr(s)) # <Shape(1,2,3,4,5) object at 139766656561792>
s.transform(nextkind)
print(repr(s)) # <Shape(2,2,3,4,5) object at 139766656561888>

How do I use the function in the class below in the other class without using global

How do I use the function in the class below in the other class without using global?
Code:
class one:
class one_one:
def add(x):
return x+1
class one_two:
ans = one.one_one.add(1)
It certainly is an unusual design, but it will work if you remember to distinguish between classes and instances of classes (objects). In your example you are attempting to call add in the class one_one which is an instance method without first instantiating an object of that class type. The example below shows one way to achieve what you are trying to do by instantiating the objects before calling their methods.
Example:
class one:
class one_one:
def add(self, x):
return x+1
class one_two:
def add(self):
a_one_one = one.one_one()
ans = a_one_one.add(1)
return ans
a_one_two = one.one_two()
print(a_one_two.add())
Output:
2

Metaclasses and methods

Adding a method to metaclass works perfectly in the below example.
class Test(object):
def __init__(self, x):
self.x = x
def double(self):
return self.x*2
# method to add
def quadruple(self):
return self.x*4
# creating metaclass
TypeTest = type('TypeTest', (Test,), {'triple': triple,
'quadruple': quadruple})
# prints 8
TypeTest(2).quadruple()
The below example doesn't work and I have no idea why. It simply doesn't recognise self in the parsed function and a TypeError occurs.
class Vehicle(object):
def __init__(self, wheels, door=False):
self.wheels = wheels
self.door = door
# method to add
def check_load(self, x):
if x > self.load:
return "Load won't fit"
else:
return "Load will fit"
# creating metaclass
Truck = type('Truck', (Vehicle,), dict(wheels=4,door=True, load=100,
check_load=check_load))
# TypeError: check_load() missing 1 required positional argument: 'x'
Truck.check_load(10)
First of all: You are not creating a metaclass, you are creating regular classes. type() is the (base) metaclass here, calling it creates a new class object (the same type of object that a class statement produces).
The first type() call is essentially equivalent to:
class TypeTest(Test)
triple = triple
quadruple = quadruple
and the second example is the same as:
class Truck(Vehicle)
wheels = 4
door = True
load = 100
check_load = check_load
You forgot to create an instance of your Truck class:
Truck.check_load(10)
This leaves the check_load() function with nothing to bind to, there is no self.
In your first example you did create an instance:
TypeTest(2).quadruple()
Notice the call, passing in 2.
Create an instance for self to be bound to:
Truck(4, True).check_load(10)
If you wanted your class to not need arguments to create an instance, you'll need to provide a different __init__ method too, one that overrides the Vehicle.__init__ method:
def init(self): pass
Truck = type('Truck', (Vehicle,), dict(
wheels=4,door=True, load=100,
check_load=check_load, __init__=init))
Now you can create the instance without arguments:
Truck().check_load(10)

Python Unbound method error?

I'm trying to inherit from this class:
class Event(Clock, Calendar):
def __init__(self):
year,month,day, hours, minutes,seconds = time.localtime()[0:6]
eClock = Clock(hours,minutes,0)
eCal = Calendar(month, day, year)
def createEvent(self,year,month,day,hours,minutes):
year,month,day = date[0:]
hours,minutes = ttime[0:2]
In order to create an event here:
sett = line[1:].split(",") # Line[1:] is going to be a
# date, such as 1/8/17 17:50.
date = sett[0]
ttime = sett[1]
ttime = ttime.split(":")
date = date.split("/")
Cevent = ttime + date
Cevent.event()
I have another class, called Reminder, that inits this:
event = Event.createEvent()
Anytime I try to run this program though, it gives me this error:
TypeError: unbound method createEvent() must be called with Event
instance as first argument (got nothing instead)
Im wondering why, and how I could take the method createEvent and use it in another class in the same file.
A bound method means that the method is called from a class. Let's look at an example:
class MyClass:
def add(self, x, y):
return x+y
vs
def add_numbers(x, y):
return x+y
The method add_numbers() is an unbound method, meaning it is not attached to any class instance. To use it, we can just call:
print(add_numbers(1, 2))
However, when we want to call the method add(), we need an instance of the class MyClass:
class_instance = MyClass()
print(class_instance.add(1, 2))
Notice that when we want to call the add() method, we first have to create a new instance of the class, then use that to call the method, Under the hood, python takes the class_instance variable and passes it to the method as the 'self' argument seen in the function definition.
In closing, your issue is in the line:
event = Event.createEvent()
The error is telling you that the method is expecting an instance of an event class, and not the class itself. If the Event class can be instantiated without arguments, then the correct syntax would be:
base_event = Event()
event = base_event.createEvent()
Of course, the method of instantiating the base_event variable will depend on the API you're trying to use.

missing 1 required positional argument:'self' when assigning a method to a variable

I am trying to assign a method's return to a variable and stuck with this error.
class MyClass():
def my_def(self):
return "Hello"
my_variable = my_def()
Here is the Java equivalent of what I want to do.
public class NewException {
public int method1(){
return 1;
}
public int variable = method1();
}
I am sure this is something simple, but I couldn't even find the right words to google this. Any help is appreciated.
Lets start with the difference between methods and functions, basically a method belongs to some object while a function does not. So for example
def myFunction():
return "F"
class MyClass:
value = 0
def myMethod(self, value):
old = self.value
self.value = value
return old
myClassInstance = MyClass()
print myClassInstance.myMethod(3)
# 0
print myClassInstance.myMethod(33)
# 3
print myFunction()
# F
Notice that the method is bound to the instance and it doesn't make sense to call the method before the instance is created. With that in mind, your error should make more sense. The method cannot be called without an instance (self). This is not the only kind of method, for example there are "static methods". Static methods are defined on the class, but they are called without an instance. For example:
class MyClass:
#staticmethod
def myStaticMethod():
return "static method"
# Consider using an instance attribute instead of a class attribute
def __init__(self):
self.instance_attribute = MyClass.myStaticMethod()
# Or if you need a class attribute it needs to go outside the class block
MyClass.class_attribute = MyClass.myStaticMethod()

Categories