Python Forum
OOP hellp (simple class person) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: OOP hellp (simple class person) (/thread-28326.html)



OOP hellp (simple class person) - onit - Jul-14-2020

Hello friends, I have started to learn OOP in python and I want some help with the simple class. I am trying to create a simple "person" class and return the birth year of the person. so I am pasting in my atemmt and the error I am geting below.

class Person:

	def __init_(self, name, age):
		self.name = name
		self.age = age 
		self.year = 2020

	def get_birth_year(self, name, age):
		print("hello" + " " + self.name)
		print("you are bourn")
		result = self.year - self.age
		print(result)


print("enter your name")
name = input()
print("enter your age")
age = input()
p1 = Person()
print(p1.get_birth_year(name,age))
Error:
Traceback (most recent call last): File "person.py", line 20, in <module> print(p1.get_birth_year(name,age)) File "person.py", line 9, in get_birth_year print("hello" + " " + self.name) AttributeError: 'Person' object has no attribute 'name'
Thanks for help it mite be something stupid or incorrect logick, but I am trying to learn OOP in python and replicate what i learned in java 5 years ago.


RE: OOP hellp (simple class person) - stullis - Jul-14-2020

Two problems:

  1. There's a typo in the __init__() function signature. You have __init_ instead of __init__. Missing a trailing underscore.
  2. When you instantiate p1, you'll need two arguments for Person().



RE: OOP hellp (simple class person) - menator01 - Jul-14-2020

I recommend that you check into python3's f-string.
That would turn this print("hello" + " " + self.name) into this print(f"hello {self.name}")


RE: OOP hellp (simple class person) - Yoriz - Jul-14-2020

Also def get_birth_year(self, name, age): should not have parameters name & age, and it should return result instead of printing it


RE: OOP hellp (simple class person) - onit - Jul-14-2020

(Jul-14-2020, 03:28 PM)stullis Wrote: Two problems:

  1. There's a typo in the __init__() function signature. You have __init_ instead of __init__. Missing a trailing underscore.
  2. When you instantiate p1, you'll need two arguments for Person().

Thanks i will look in to this. Yep spelling mistakes hapins for me more often then i want them, using a screenreader when you are coding has some cons and that one is for sure...