Jump to content

More Python help.

Flyguygamer
Go to solution Solved by Adnanklink,

self._name instead?

Still in the learning process and am running in to issues with class def items. 

 

Here is the code.

class Animal:	def __init__(self, name = 'No Name'):		self._name = name			def set_name(self, name = 'No Name'):		self._name = name			def get_name(self):		return self.name			def noise(self):		print("Errrrrr")			def move(self):		print("Moving Forward")				def eat(self):		print("Crunch, Chruch")		dog = Animal()dog.noise()dog.move()dog.eat()dog.set_name("Parker")print(dog.get_name())

And here is the error from eclipse.

ErrrrrrMoving ForwardCrunch, ChruchTraceback (most recent call last):  File "C:\Users\Jake.JakeHuitt-HP\workspace\learning python\Learning_python.py", line 27, in <module>    print(dog.get_name())  File "C:\Users\Jake.JakeHuitt-HP\workspace\learning python\Learning_python.py", line 9, in get_name    return self.nameAttributeError: 'Animal' object has no attribute 'name'

Thanks in advance, Jake.

Link to comment
Share on other sites

Link to post
Share on other sites

-

You can do all of this in one function if you want to print the dog name straight away, use the print outside if you're wanting to call it later.

class Animal:	def name(name):		name="Parker"		print(name)		return name	def noise(self):		print("Errrrrr")			def move(self):		print("Moving Forward")				def eat(self):		print("Crunch, Chruch")					dog = Animal() dog.noise()dog.move()dog.eat()dog.name()

If you wanted to use it in another part of the program you can use:

print(dog.name())

Although this doesn't really answer your question. The reason (i think) why it doesn't run is because get_name is not part of dog, but set_name is.

 

Edit: Out of interest what does self do?

Link to comment
Share on other sites

Link to post
Share on other sites

You can do all of this in one function if you want to print the dog name straight away, use the print outside if you're wanting to call it later.

class Animal:	def name(name):		name="Parker"		print(name)		return name	def noise(self):		print("Errrrrr")			def move(self):		print("Moving Forward")				def eat(self):		print("Crunch, Chruch")					dog = Animal() dog.noise()dog.move()dog.eat()dog.name()

If you wanted to use it in another part of the program you can use:

print(dog.name())

Although this doesn't really answer your question. The reason (i think) why it doesn't run is because get_name is not part of dog, but set_name is.

 

Edit: Out of interest what does self do?

Not quite sure. I am following this tutorial. 

 

https://www.youtube.com/watch?v=pF7xdh4DW-o#t=205

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×