如何使用@classmethod将值传递给方法 [英] How to pass values to a method with @classmethod

查看:121
本文介绍了如何使用@classmethod将值传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我已经教了大约一个月了,我现在正在学习@classmethod。

我认为它像Java这样的语言是私有的,但我不确定。我想了解它的作用。我决定创建这个小程序



  class 你好:
def __init __(self,name):
self.name = name

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

def 回复(个体经营):
返回 self.say_hello()


Justine = Hello( Justine
Justine.reply( )





我的尝试:



因为@classmethod的方法有

 cls 



作为第一个参数

我将自己改为cls仍然出现错误(AttributeEr ror:类型对象'Hello'没有属性'name'

解决方案

你已经宣布 say_hello 作为一个类方法,这意味着它不能访问属于实例对象的变量,只能访问类变量。删除 @classmethod 声明,它将起作用。



参见 9。类 - Python 3.7.1文档 [ ^ ]。

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

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

cls


as first parameter
I changed self to cls still am getting an error (AttributeError: type object 'Hello' has no attribute 'name'

解决方案

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[^].


这篇关于如何使用@classmethod将值传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆