TypeError when adding variable [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I took working example code and tried to add another variable self.species = martian under the init method. Seems you cannot do this which doesn't make sense to me.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name, species):
self.name = name
self.species = martian
# Sample Method
def say_hi(self, name, species):
print('Hello, my name is', self.name)
print('I am', self.species)
p = Person('Martin')
p.say_hi()
TypeError: __init__() missing 1 required positional argument: 'species'

When creating the person p you need to pass the species parameter. As well, you are not using that argument in your function.
Calling could look like this:
p = Person("Martin", "martian")
Then within the constructor you reference the argument like this:
self.species = species

this is how your code should look like.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name, species):
self.name = name
self.species = species
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
print('I am', self.species)
p = Person('Martin', 'martian')
p.say_hi()
I suggest you watch some other beginner's video lectures on 'init' method and 'Object oriented programming in python' before writing these type of codes otherwise it would be very hard to understand beyond this point

Related

Python - init argument not used in self [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I came by a code and wanted to get more understanding on when to use such arrangement.
What would be a good scenario of not using __init__'s argument (name) in self?
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
user_one = ArgumentNotUsedInSelf("Mike")
print(user_one.type)
Any explanations from architectural (and not only) point of view are most welcome!
Some of the reasons for this can be:
Historical. The class used to use the argument, but it was changed so it's no longer meaningful. The argument was kept for backward compatibility.
Class hierarchy. This may be a child class of a class that uses the argument, but the child overrides the need for it. The argument is required for compatibility with the parent.
Sort of Barmar's historical example... let's say:
ArgumentNotUsedInSelf used to do something with name, but now doesn't.
But name is still used in SubClass, and changing everything could mess up dependent programs.
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
class SubClass(ArgumentNotUsedInSelf):
def __init__(self, name):
super(SubClass, self).__init__(name)
self.name = name
x = SubClass('Mike')
print(x.name, x.type)
Output:
Mike user
This would be helpful if you want to store the field "name" of the created object and re-use it later:
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
self.name = name
user_one = ArgumentNotUsedInSelf("Mike")
print(user_one.type)
print(user_one.name)

Python learner -- trouble creating a class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I cannot figure out why this simple Python code to create a class called Resto will not run. The traceback says the name "Resto" is not defined (at the end of the code where I am making an instance of the class). But I successfully created other classes by following this exact format.
class Resto:
""" a model of a restaurant """
def __init__(self, name, cuisine):
""" attributes of the restaurant """
self.name = name
self.cuisine = cuisine
def describe_resto(self):
print (f"{self.name} features {self.cuisine} cooking.")
def resto_open(self):
print (f"{self.name} is open Tuesday through Sunday, from 6 to midnight.")
Alices = Resto ("Alice's", "Canadian")
Alices.describe_resto()
Alices.resto_open()
I think it is because Alices = Resto (...) line and the lines after that line is indented on the same level as the stuff inside Resto.
Try removing their indentation (make them align to the left with no spaces).
You must instantiate the class outside of the class itself, because at the time of execution, the class doesn't yet exist. It is trying to execute the lines to create an instance of the class, inside of the uninstantiated class itself. So un-indent the last 3 lines:
class Resto:
""" a model of a restaurant """
def __init__(self, name, cuisine):
""" attributes of the restaurant """
self.name = name
self.cuisine = cuisine
def describe_resto(self):
print (f"{self.name} features {self.cuisine} cooking.")
def resto_open(self):
print (f"{self.name} is open Tuesday through Sunday, from 6 to midnight.")
Alices = Resto ("Alice's", "Canadian")
Alices.describe_resto()
Alices.resto_open()
Output:
Alice's features Canadian cooking.
Alice's is open Tuesday through Sunday, from 6 to midnight.

Variable scope in __init__ method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
class Person(object):
def __init__(self, age):
self.age = age
self.ageGroup = ageGroup
def findAgeGroup(self):
if age >= 80:
ageGroup= "old"
print ageGroup
John= Person(95)
John.findAgeGroup
So my Question is probably a pretty simple one. In the above code in the __init__ method the variable self.age is set when a new instance of the Person class is instantiated? And all of the other variables in the __init__ method are put there because they are related to self.age? For example in the findAgeGroup method age is used to derive a value for ageGroup. So would the only time you list self.ageGroup in the __init__ method be if you plan to derive the value from self.age which is called in when a new instance of the class is created?
In Python you actually always need the self to reference instance variables unlike e.g. Java's this:
def findAgeGroup(self):
if self.age >= 80:
self.ageGroup = "old"
print self.ageGroup
# also Python prefers snake_case: self.age_group

python error NameError name is not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
class Bird :
'''A base class to define bird properties.'''
count = 0
def_init_( self , chat )
self.sound = chat
Bird.count += 1
def talk( self ) :
return self.sound
NameError: name 'def_init_' is not defined
I tried using 2 underscores on both side of the 'init'
This looks like a simple typo. You're missing the space after def - it should be:
def __init__(self, chat):
you had lots of error in your script actually
1> indentation
2> give space after def
3> colon after def init( self , chat )
follow the rules then everything will be okay....
class Bird :
'''A base class to define bird properties.'''
count = 0
def __init__( self , chat ):
self.sound = chat
Bird.count += 1
def talk( self ):
return self.sound
You need to change your _init_ function to def __init__(self, chat):.
The __ is called a dunder, which is short for 'double underscore'. We usually use this, magic methods like instantiation. So for example, [] would be called __get__.
Whenever you see a dunder, you know it has a special use.

calling a function in python got nothing instead [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I got a code like this.
....
class SocketWatcher(Thread):
....
def run(self):
....
TicketCounter.increment() # I try to get this function
...
....
class TicketCounter(Thread):
....
def increment(self):
...
when I run the program I got this error.
TypeError: unbound method increment() must be called with TicketCounter instance as first argument (got nothing instead)
i there any way that I can call the increment() function from TicketCounter Class to the SocketWatcher Class? or Does my calling is wrong...
You must create an instance of the class TicketCounter first before you can call any functions from it:
class SocketWatcher(Thread):
....
def run(self):
....
myinstance = TicketCounter()
myinstance.increment()
Otherwise the method is not bound anywhere. Creating an instance binds the method to the instance.
Member functions are part of the instances of a Class. So whenever you want to call you must always call it with an instance of the Class and not the Class name itself.
You could do:
TicketCounter().increment()
What this does is that it initialises an object and then calls this function. The following example will make it clear.
class Ticket:
def __init__(self):
print 'Object has been initialised'
def counter(self):
print "The function counter has been invoked"
And the output to illustrate this:
>>> Ticket().counter()
Object has been initialised
The function counter has been invoked
>>>
You are passing self, so I'm assuming that you need to create an instance. But if the method really doesn't need an instance then you can use the #classmethod or #staticmethod decorators and your code would work:
class TicketCounter(Thread):
#classmethod
def increment(cls):
...
or
class TicketCounter(Thread):
#staticmethod
def increment():
...
both can be called as TicketCounter.increment()

Categories

Resources