I am new to Python and I am just trying to make a simple class to test it out. I used the self argument while defining my method in the "Patient" class but I am still getting the "takes no arguments error" when I try to build. Here is the code I'm trying to run...
class Patient:
def _init_(self,name,weight=0,LegLen=0):
self.name = name
self.weight = weight
self.LegLen = LegLen
Mark = Patient('Mark')
print(Mark.name)
then I get the error...
Mark = Patient('Mark')
TypeError: Patient() takes no arguments
What am I doing wrong?
The _init_ should be spelled __init__ (double underscores). Otherwise it's just a method like any other and not a constructor.
Related
I'm new at programming and I'm learning Python. The code should be very simple. The goal should be implement a calculator that does additions between numbers.
It returns this error:
init() missing 1 required positional argument: 'number_2'
So it's like it reads self as a parameter, but I can't figure out why.
I'm using Linux Ubuntu 19 as operative system.
Here's my code:
class Calculator:
def __init__(self, number_1, number_2):
self.number_1=number_1
self.number_2=number_2
def add(self):
print(f"{number_1}+{number_2}={number_1+number_2}")
if __name__=="__main__":
c=Calculator('Casio')
c.add(2,3)
It isn't reading self as a parameter here, but 'Casio' which it is storing as number_1. As the error message reads, it is missing number 2. If you want add() to be able to take arbitrary values, you will need to add them as arguments to that method rather than to the __init__() function.
You have to pass parameters to the add function and not to __init__ which instantiates the class.
class Calculator:
def __init__(self, name):
self.name=name
def add(self, number_1, number_2):
print(f"{number_1}+{number_2}={number_1+number_2}")
if __name__=="__main__":
c=Calculator('Casio')
c.add(2,3)
When you are initializing the object 'c', you are running the init method, and you therefore need to pass in both parameters to the init method. So, you are required to give both 'number_1' and 'number_2' when you create the object. You passed in only'Casio', which python is interpreting as 'number_1'. Python is also interpreting that there is no 'number_2'. Here are some solutions:
1: You could make the add() function have the two arguments that init has ('number_1' and 'number_2') and have the only arguments for init be self and 'name'. Then, you could have the init method only do self.name = name and nothing else. 2: You could make the arguments 'number_1' and 'number_2' optional by making a default variable for them if you do not enter it:
def __init__(self, number_1="1", number_2="2"):
I have 2 scripts, 1st is All_Methods, and another is All_Testcases, as I am using unittest framework, so here we go.
All_Methods is like:
class All_Services():
def abc(self):
x =1
def bca(self):
print "My Name is Taimoor"
self.abc()
def cba(self):
self.bca()
and on another script which is All_TestCases is like this:
from All_Methods import All_Services as service
class All_TestCases(unittest.TestCase):
def test_1_running_method(self)
service.cba(self)
Exception showing is:
AttributeError: 'All_TestCases' object has no attribute 'bca'
Kindly someone tell me, what I am missing here?
Thanks.
You are not using classes in the usual way when you pass in self to methods that you call on the class. Common is to call the methods on instances of the class and getting the self argument implicitly.
When you call Method.running_query_Athena(self) self is an instance of All_TestCases which does not have the method connecting_Athena.
Did you mean for All_TestCases to derive from All_Methods?
Why is All_Methods a class at all?
Use proper indentation since python is solely based on the basis of how the code is indented.
Please, Please use proper naming conventions; as advised under PEP 8.
You're trying to access an instance method without an instance.
Try the following:
class MyClass:
def my_instance_method(self):
return True
#classmethod
def my_class_method(cls):
return True
#staticmethod
def my_static_method():
return True
This won't work:
>> MyClass.my_instance_method()
TypeError: my_instance_method() missing 1 required positional argument: 'self'
but these will since they are not bound to a class instance being created.
MyClass.my_class_method()
MyClass.my_static_method()
An instance method requires that you instantiate the Class; meaning you use:
MyClass().my_instance_method()
Since you seem to want to set response_id on the class instance; using the self argument which denotes the class instance to get the response_id. - I suggest that you use an instance method and instantiate the class as shown above (note the () after the class name)
Kindly do fix your formatting in the question.
There are quite a few things wrong with the code in the example, but putting that aside.
The error is caused by passing an instance of class A as the self argument to a (non-static) method of class B.
Python will attempt to call this method on the instance of class A, resulting in the missing attribute error.
Here is a simplified example of the problem:
class A:
def is_ham(self):
# Python secretly does `self.is_ham()` here,
# because `self` is the current instance of Class A.
# Unless you explicitly pass `self` when calling the method.
return True
class B:
def is_it_ham(self):
# Note, `self` is an instance of class B here.
return A.is_ham(self)
spam = B()
spam.is_it_ham()
I come from a .NET and Javascript background and I'm working my way up to learn Python (for Raspberry Pi).
Right now I'm trying to figure out OOP in Python and the use of methods and classes. But having a little issue with #staticmethod
class Car(object):
"""description of class"""
def __init__(self, make, model):
self.make = make
self.model = model
#staticmethod
def makeFirstNoise():
print("Vrooooommm!")
def makeSecondNoise():
print("Mweeeeeeeeeh!")
This is how I implement my class and try to run both methods.
from Car import Car
mustang = Car('Ford', 'Mustang')
mustang.makeFirstNoise()
mustang.makeSecondNoise()
This is the output:
Vrooooommm!
Traceback (most recent call last):
File "D:\Dev\T\PythonHelloWorld\PythonHelloWorld\PythonHelloWorld.py", line 5, in <module>
mustang.makeSecondNoise()
TypeError: makeSecondNoise() takes 0 positional arguments but 1 was given
So question, why can't I execute the second method without my staticmethod attribute? This seems to work if I just return the text directly like this:
def makeSecondNoise():
return "Mweeeeeeeh!"
print(mustang.makeSecondNoise())
The reason makeSecondNoise is causing an error is because it is automatically passed one argument, self, because it's not declared as a staticmethod. self is the instance of the class that the function was called on. This is ultimately causing the error because makeSecondNoise isn't coded to accept any parameters; it'd be like doing this:
def something():
...
something("Foo")
Here's an example of how self works:
>>> class Car:
... def makenoise(self):
... print(self)
...
>>> mustang = Car()
>>> mustang.makenoise()
<__main__.Car object at 0x0000000005498B38> # We can see that "self" is a reference to "mustang"
Your problem isn't related to print (I couldn't get your example without print to work either) - it's related to the automatic passing of the self argument.
In Python all method calls (besides classmethods and staticmethods) explicitly passed object instance as first argument. Convention is to name this argument self. This explicit argument should be included in method signature:
class Car(object):
def makeSecondNoise(self): # note that method takes one argument
print("Mweeeeeeeeeh!")
After that you may call your method without any problems.
mustang = Car('Ford', 'Mustang')
mustang.makeSecondNoise()
In Java, this (which represents instance object) is passed implicitly to methods - this is a source of your confusion.
I have a class with a method. Now, I put that class inside a list.
When I'm trying to print a method, I do:
print(listname[pointer].method)
But when I compile it says that objects does not support indexation.
The exact code goes like this:
class hero():
def __init__(self, heroname):
self.h=heroname
herolist=[]
herolist.append(hero)
print(herolist[0].h)
I'm expecting that the code will print the hero name, but it doesn't. What am I doing wrong?
EDIT:
Sorry, I forgot to show it in the code but outside of the class I did instantiate the object I am trying to call. To be exact, I did something like:
heroone=hero()
heroone.h='jude'
You have a few problems. First of all, the name of the initialization method is __init__ (two underscores on each side), not ___init___. Second, by appending hero you are appending the class itself. The class itself does not have an h attribute. Only instances of it will have an h attribute, because __init__ is only called when you create an instance. Third, you forgot the self argument in your __init__ method. And fourth, you apparently wrote __init__ to expect a "heroname" argument, but you don't pass any such argument. (You don't pass any arguments, since you never instantiate the class.)
Try this:
class hero():
def __init__(self, heroname):
self.h = heroname
herolist=[]
herolist.append(hero('Bob the Hero'))
print(herolist[0].h)
You store the class definition, not an instanced objet, which means that heroname doesn't have a value. You could write :
herolist.append(hero('Achile'))
and your example will work as expected.
You are using three _ with init method because of which constructor is not called.
two _ are needed on both side init.
To assign name to h pass it to init method.
Use CamelCase to namethe class
Below is working code:
class Hero():
def __init__(self, heroname):
self.h = heroname
herolist=[]
herolist.append(Hero('Dude'))
print(herolist[0].h)
Do like this:-
class Hero():
def __init__(self, heroname):
self.h=heroname
herolist=[]
Now you can do:
h1 = Hero('jude')
herolist.append(h1)
print herolist[0].h
or even simpler:
herolist.append(Hero('Hero'))
print herolist[0].h
I am learning Django and understand that the __init__() function is used to construct object from certain class. However,I also see some class code without a __init__() class function, so my question is that is the __init__() function really necessary for all class? And you might also correct me if there is anything wrong with my understanding of this function. Thank you.
Check out the documentation on Class objects
The __init__() function is called when the object is created:
>>> class MyBoringClass(object):
def __init__(self):
print 'Being initialised!'
>>> b = MyBoringClass()
Being initialised!
It can also accept parameters:
>>> class MyInterestingClass(object):
def __init__(self, name):
print 'Initialised as {}'.format(name)
self.name = name
>>> i = MyInterestingClass('Mona')
Initialised as Mona
>>> i.name
Mona
If you don't need it, then don't use it.
By the way, Django is a web framework written in Python - __init()__ comes from Python.