Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to python, I've been teaching myself for about a month, am now learning about @classmethod.
I see it as private in languages like Java am not sure though. I want to understand what it does. I decided to create this small program

Python
class Hello:
	def __init__(self, name):
	self.name = name

	@classmethod
	def say_hello(self):
	print("Hello {}".format(self.name))

	def reply(self):
	return self.say_hello()


Justine = Hello("Justine") 
Justine.reply()


What I have tried:

Since methods with @classmethod have
Python
cls

as first parameter
I changed self to cls still am getting an error (AttributeError: type object 'Hello' has no attribute 'name'
Posted
Updated 18-Nov-18 1:51am
v2

1 solution

You have declared say_hello as a class method, which means that it does not have access to variables that belong to an instance object, only to class variables. Remove the @classmethod declaration and it will work.

See 9. Classes — Python 3.7.1 documentation[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900