class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
args, varargs, keywords, defaults = inspect.getargspec(getattr(globals()['Dog'](), 'description'))'''
上面的代码给出以下错误消息:
args, varargs, keywords, defaults =
inspect.getargspec(getattr(globals()['Dog'](), 'description'))
TypeError: __init__() takes exactly 3 arguments (1 given)
但是,如果我愿意。
args, varargs, keywords, defaults = inspect.getargspec(getattr(Dog, 'description'))
..我没有任何错误。
当我想从另一个文件访问一个文件的类名和函数名时,我只有名称字符串,这就是为什么我尝试使用前一种方法会给我带来错误的原因。
对此有什么解决方案?
答案 0 :(得分:0)
该错误表示您正在尝试实例化Dog
,但是没有name
和age
参数:
args, varargs, keywords, defaults = inspect.getargspec(getattr(globals()['Dog'](), 'description'))
^ here
在您的最后一小段代码中,您没有实例化Dog
。
也许您打算省略括号:
args, varargs, keywords, defaults = inspect.getargspec(getattr(globals()['Dog'], 'description'))
更新:
还要注意,自Python3.0 getargspec()
起已弃用。
建议使用signature()
或getfullargspec()
,它们各自返回不同的类型。
答案 1 :(得分:0)
您几乎在正确的轨道上。但是,您没有正确初始化Dog
类。为了使description
方法起作用,您必须使用两个参数Dog('scooby', 10)
初始化类,其中scooby
是 dogname 和 10 狗狗。
import inspect
class Dog:
# Class Attribute
species = "mammal"
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
让我们以字符串形式运行description
方法:
getattr(globals()["Dog"]("scooby", 10), "description")()
这表明:
>> 'scooby is 10 years old'
让我们以字符串形式运行speak
方法。请注意speak
方法如何接受一个额外的参数:
getattr(globals()["Dog"]("scooby", 10), "speak")("woof")
这表明:
>> 'scooby says woof'