Hi I just started with Python, I'm currently developing a UI testing application for mobile devices and I have to work on a custom rendered Softkeyboard.
Button.py
class Button():
def __init__(self, name, x, y, x2=None, y2=None):
self.name = name
self.x = x
self.y = y
self.x2 = x2
self.y2 = y2
KeyboardKey.py
import Button
class KeyboardKey(Button):
def __init__(self, name, x, y):
super(self.__class__, self).__init__(name, x, y)
That's my error:
Traceback (most recent call last):
File "/home/thomas/.../KeyboardKey.py", line 2, in
class KeyboardKey(Button):
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
The way you do in your code, you inherit from module Button, not a class. You should inherit class Button.Button instead.
In order to avoid this in future, I strongly suggest to name modules with lowercase, and capitalize classes. So, better naming would be:
import button
class KeyboardKey(button.Button):
def __init__(self, name, x, y):
super(self.__class__, self).__init__(name, x, y)
Modules in python are normal objects (of type types.ModuleType), can be inherited, and have __init__ method:
>>> import base64
>>> base64.__init__
<method-wrapper '__init__' of module object at 0x00AB5630>
See usage:
>>> base64.__init__('modname', 'docs here')
>>> base64.__doc__
'docs here'
>>> base64.__name__
'modname'
Related
I have been trying this many times but it does not work
when I call an instance with the attribute breed, I get an error that an attribute breed is not available !
Do not forget to pass argument(s)
class Foo():
def __init__(self, x, y):
self.x = x
self.y = y
f = Foo(1, 2)
f.x # 1
f.y # 2
https://docs.python.org/3/tutorial/classes.html
There are the following faults
class Cat: # No paranthesis here
def __init__(self, breed): # use double underscores
self.breed = breed
In your code, the breed attribute is not created as you have written _init_ instead of __init__, but now it will be created and the error that the attribute isn't available will be resolved.
Secondly,
my_cat = Cat('Scottish Fold') # You need to pass the argument
I have this code:
import numpy as np
class Person:
...
class Bob:
def __init__(self, age, gender="Male"):
self.age = age
self.gender = gender
def walk(x):
return x / (180 * np.exp(-self.age / 35))
bob_1 = Person().Bob(37)
I want it to call the walk(x) function when calling bob_1(x) but still be able to call other methods as bob_1.method(args).
Would Python happen to provide a way to do so?
Defining a class within a class makes the inner class count as a class-level variable, not an instance variable.
Doing this should work:
bob_1 = Person.Bob(37) # note that we're not calling Person
print(bob_1.walk(30))
Note that .walk() is currently defined as a class method - to make it an instance method, you should define it as
def walk(self, x):
The self is passed implicitly when you call the method on an instance like bob_1.
If you want to have an instance display some behavior when you call it, then you can define the __call__() method on the class:
>>> class A:
... def __call__(self, *args):
... print(args)
...
>>> g = A()
>>> g(3, 4, 5)
(3, 4, 5)
In your case, in order to make bob_1(30) behave like bob_1.walk(30), you would do
def __call__(self, x):
return self.walk(x)
From a class called heatnet I like to return instance A stored in list[0].
In the Main file I like to call all functions that are related to the instance. This functions shall be shown from the autocomplete by spyder or PyCharm. Tried rope, jedi etc. The run works but not the autocomplete at writing.
from Pipe import Pipe
class Heatnet(object):
def __init__(self, iteminstance):
print(iteminstance)
self.list = []
self.list.append(Pipe(iteminstance[0], iteminstance[1]))
def pipes(self, i = slice(None, None)):
return self.list[i]
class Pipe:
def __init__(self, x, y):
self.x = x
self.y = y
def area(self):
return self.x * self.y
heatnet.pipes(0).area()
I solved it:
Dont make list of instances private. If it is protected or public autocompletion works properly.
I am trying to understand Python multiple inheritance and I kind of understand MRO, super() and passing arguments in MI, but while I was reading the below example it kind of confused me.
class Contact:
all_contacts = []
def __init__(self, name=None, email=None, **kwargs):
super().__init__(**kwargs)
self.name = name
self.email = email
self.all_contacts.append(self)
class AddressHolder:
def __init__(self, street=None, city=None, state=None, code=None, **kwargs):
super().__init__(**kwargs)
self.street = street
self.city = city
self.state = state
self.code = code
class Friend(Contact, AddressHolder):
def __init__(self, phone='', **kwargs):
super().__init__(**kwargs)
self.phone = phone
Now what I fail to understand is why use super() in Contact and AddressHolder class. I mean super() is used when we are inheriting from a parent class but both Contact & AddressHolder are not inheriting from any other class. (technically they are inheriting from object). This example confuses me with the right use of super()
All (new style) classes have a linearized method resolution order (MRO). Depending on the inheritance tree, actually figuring out the MRO can be a bit mind-bending, but it is deterministic via a relatively simple algorithm. You can also check the MRO through a class's __mro__ attribute.
super gets a delegator to the next class in the MRO. In your example, Friend has the following MRO:
Friend -> Contact -> AddressHolder -> object
If you call super in one of Friend's methods, you'll get a delegator that delegates to Contact's methods. If that method doesn't call super, you'll never call the methods on AddressHolder. In other words, super is responsible for calling only the next method in the MRO, not ALL the remaining methods in the MRO.
(If you call super in one of Friend's methods and Contact doesn't have its own implementation of that method, then super will delegate to AddressHolder, or whichever class has the next implementation for that method in the MRO.)
This is all well and good since object has a completely functional __init__ method (so long as **kwargs is empty at that point). Unfortunately, it doesn't work if you are trying to resolve the call chain of some custom method. e.g. foo. In that case, you want to insert a base class that all of the base classes inherit from. Since that class is a base for all of the classes (or at least base classes) to inherit from. That class will end up at the end of the MRO and can do parameter validation1:
class FooProvider:
def foo(self, **kwargs):
assert not kwargs # Make sure all kwargs have been stripped
class Bar(FooProvider):
def foo(self, x, **kwargs):
self.x = x
super().foo(**kwargs)
class Baz(FooProvider):
def foo(self, y, **kwargs):
self.y = y
super().foo(**kwargs)
class Qux(Bar, Baz):
def foo(self, z, **kwargs):
self.z = z
super().foo(**kwargs)
demo:
>>> q = Qux()
>>> q.foo(x=1, y=2, z=3)
>>> vars(q)
{'z': 3, 'y': 2, 'x': 1}
>>> q.foo(die='invalid')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'z'
>>>
>>> q.foo(x=1, y=2, z=3, die='invalid')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/google/home/mgilson/sandbox/super_.py", line 18, in foo
super().foo(**kwargs)
File "/usr/local/google/home/mgilson/sandbox/super_.py", line 8, in foo
super().foo(**kwargs)
File "/usr/local/google/home/mgilson/sandbox/super_.py", line 13, in foo
super().foo(**kwargs)
File "/usr/local/google/home/mgilson/sandbox/super_.py", line 3, in foo
assert not kwargs # Make sure all kwargs have been stripped
AssertionError
Note, you can still have default arguments with this approach so you don't lose too much there.
1Note, this isn't the only strategy to deal with this problem -- There are other approaches you can take when making mixins, etc. but this is by far the most robust approach.
So I am having some trouble with inheritance in python. I have two classes. The first is
class Base1DHeatEquation:
def __init__(self, alpha, final_time, time_discrete):
self.alpha = alpha
self.final_time = final_time
self.time_discrete = time_discrete
#Additional Functions which aren't causing a problem
and the second is a class which inherits the first
class IntialValueTest1DHE(Base1DHeatEquation):
def __init__(self, alpha, final_time, time_discrete,intialValues,\
x_discrete ,noise):
super(IntialValueTest1DHE,self).__init__(self, alpha, final_time, time_discrete)
self.intialValues = intialValues
#Additional Functions which aren't causing a problem
The problem is when I trying to create an IntialValueTest1DHE object, I get the following
>>> import HeatEquation1D as he #The File where both classes are stored
>>> temp = he.IntialValueTest1DHE(1,1,100,np.sin,100,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 4 arguments (7 given)
It seems like object creation is trying to access the init from the parent class in stead of the child class and I am not sure how to fix that.
You don't need to add "self" to super() declaration. Also, you should use "new style" classes:
class Base1DHeatEquation(object):
def __init__(self, alpha, final_time, time_discrete):
self.alpha = alpha
self.final_time = final_time
self.time_discrete = time_discrete
class IntialValueTest1DHE(Base1DHeatEquation):
def __init__(self, alpha, final_time, time_discrete,intialValues,
x_discrete ,noise):
super(IntialValueTest1DHE,self).__init__(alpha, final_time, time_discrete)
self.intialValues = intialValues