Zer*_*eus 210 python methods arguments self python-3.x
如果我上课了......
class MyClass:
def method(arg):
print(arg)
Run Code Online (Sandbox Code Playgroud)
...我用来创建一个对象......
my_object = MyClass()
Run Code Online (Sandbox Code Playgroud)
......我就这样打电话method("foo")......
>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)
Run Code Online (Sandbox Code Playgroud)
...为什么Python告诉我我给了它两个参数,当我只给出一个?
Zer*_*eus 284
在Python中,这个:
my_object.method("foo")
Run Code Online (Sandbox Code Playgroud)
...是语法糖,解释器在幕后翻译成:
MyClass.method(my_object, "foo")
Run Code Online (Sandbox Code Playgroud)
...正如你所看到的,确实有两个参数 - 从调用者的角度来看,只是第一个是隐含的.
这是因为大多数方法都会对它们被调用的对象进行一些处理,因此需要有一些方法可以在方法内引用该对象.按照惯例,self在方法定义中调用第一个参数:
class MyNewClass:
def method(self, arg):
print(self)
print(arg)
Run Code Online (Sandbox Code Playgroud)
如果你调用method("foo")一个实例MyNewClass,它按预期工作:
>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo
Run Code Online (Sandbox Code Playgroud)
偶尔(但不经常),你真的不关心你的方法绑定的对象,在这种情况下,你可以使用builtin 函数来装饰方法,staticmethod()这样说:
class MyOtherClass:
@staticmethod
def method(arg):
print(arg)
Run Code Online (Sandbox Code Playgroud)
...在这种情况下,您不需要self在方法定义中添加参数,它仍然有效:
>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo
Run Code Online (Sandbox Code Playgroud)
sim*_*eco 23
用简单的话来说。
在 Python 中,您应该将self参数添加为类中所有已定义方法的第一个参数:
class MyClass:
def method(self, arg):
print(arg)
Run Code Online (Sandbox Code Playgroud)
然后你可以根据你的直觉使用你的方法:
>>> my_object = MyClass()
>>> my_object.method("foo")
foo
Run Code Online (Sandbox Code Playgroud)
这应该可以解决您的问题:)
为了更好地理解,您还可以阅读这个问题的答案:自我的目的是什么?
Sta*_*ich 14
Python 的新手,当我**以错误的方式使用 Python 的功能时,我遇到了这个问题。试图从某个地方调用这个定义:
def create_properties_frame(self, parent, **kwargs):
Run Code Online (Sandbox Code Playgroud)
使用没有双星的呼叫导致了问题:
self.create_properties_frame(frame, kw_gsp)
Run Code Online (Sandbox Code Playgroud)
类型错误:create_properties_frame() 需要 2 个位置参数,但给出了 3 个
解决方案是**在参数中添加:
self.create_properties_frame(frame, **kw_gsp)
Run Code Online (Sandbox Code Playgroud)
小智 12
遇到此类错误时需要考虑的其他事项:
我遇到此错误消息,发现这篇文章很有帮助.在我的情况下,我已经覆盖了一个init(),其中有对象继承.
继承的示例相当长,所以我将跳到一个不使用继承的更简单的示例:
class MyBadInitClass:
def ___init__(self, name):
self.name = name
def name_foo(self, arg):
print(self)
print(arg)
print("My name is", self.name)
class MyNewClass:
def new_foo(self, arg):
print(self)
print(arg)
my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")
Run Code Online (Sandbox Code Playgroud)
结果是:
<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters
Run Code Online (Sandbox Code Playgroud)
PyCharm没有抓住这个错字.Notepad ++也没有(其他编辑/ IDE可能).
当然,这是一个"不带参数"的TypeError,在Python中的对象初始化方面,与期望一个"得到两个"没什么不同.
解决主题:如果语法正确,将使用重载初始化程序,但如果不是,它将被忽略,而内置使用.该对象不会期望/处理此错误并抛出错误.
在sytax错误的情况下:修复很简单,只需编辑自定义init语句:
def __init__(self, name):
self.name = name
Run Code Online (Sandbox Code Playgroud)
正如其他答案中提到的 - 当您使用实例方法时,您需要self作为第一个参数传递- 这是错误的根源。
除此之外,重要的是要了解只有实例方法才能self作为第一个参数来引用实例。
如果方法是静态的,则不传递self,而是传递cls参数(或class_)。
请看下面的例子。
class City:
country = "USA" # This is a class level attribute which will be shared across all instances (and not created PER instance)
def __init__(self, name, location, population):
self.name = name
self.location = location
self.population = population
# This is an instance method which takes self as the first argument to refer to the instance
def print_population(self, some_nice_sentence_prefix):
print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")
# This is a static (class) method which is marked with the @classmethod attribute
# All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
@classmethod
def change_country(cls, new_country):
cls.country = new_country
Run Code Online (Sandbox Code Playgroud)
一些测试只是为了让事情更清楚:
# Populate objects
city1 = City("New York", "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")
#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!
#2.A) Use the static method in the object
city2.change_country("Canada")
#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada
Run Code Online (Sandbox Code Playgroud)
当您未指定参数no __init__()或任何其他要查找的方法时,就会发生这种情况。
例如:
class Dog:
def __init__(self):
print("IN INIT METHOD")
def __unicode__(self,):
print("IN UNICODE METHOD")
def __str__(self):
print("IN STR METHOD")
obj=Dog("JIMMY",1,2,3,"WOOF")
Run Code Online (Sandbox Code Playgroud)
当您运行上述程序时,它会给您这样的错误:
TypeError:__init __()接受1个位置参数,但给出了6个
我们如何摆脱这件事?
只需传递参数,__init__()寻找什么方法
class Dog:
def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
self.name_of_dog = dogname
self.date_of_birth = dob_d
self.month_of_birth = dob_m
self.year_of_birth = dob_y
self.sound_it_make = dogSpeakText
def __unicode__(self, ):
print("IN UNICODE METHOD")
def __str__(self):
print("IN STR METHOD")
obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))
Run Code Online (Sandbox Code Playgroud)
小智 6
如果想在不创建对象的情况下调用方法,可以将方法更改为静态方法。
class MyClass:
@staticmethod
def method(arg):
print(arg)
MyClass.method("i am a static method")
Run Code Online (Sandbox Code Playgroud)
小智 5
当我睡眠不足时,我会收到此错误,并使用def而不是创建一个类class:
def MyClass():
def __init__(self, x):
self.x = x
a = MyClass(3)
-> TypeError: MyClass() takes 0 positional arguments but 1 was given
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
410748 次 |
| 最近记录: |