简体   繁体   English

无法在Python中调用方法

[英]Unable to call method in Python

Right now I have a method in my class that's really simple, but I'm have a hard time calling it. 现在,我的班级中有一个非常简单的方法,但是我很难调用它。

def size(self):
  return self.size

The call I'm required to use is this: 我需要使用的呼叫是这样的:

print(str(ll.size()))

Which always leads to this output: 总是导致以下输出:

print(str(ll.size()))
TypeError: 'int' object is not callable

I've been told several times it's the way I have the size() method set up, but I've never been able to understand it. 我已经多次被告知这是我设置size()方法的方式,但是我从来没有能够理解它。 Can someone show me the proper way to make a method that can be called like this and explain the difference for future reference? 有人可以向我展示制作这样的方法的正确方法,并解释其区别以供将来参考吗? Thanks! 谢谢!

It seems like your class has two attributes called size , one being the method you have defined and one being the property you're calling from inside your method. 看来您的类具有两个名为size属性,一个是您定义的方法,另一个是您要从方法内部调用的属性。

From the error message you can tell that the second one is begin called. 从错误消息中可以看出第二个已开始调用。 So, ll.size is an int and ll.size() is 'calling' that int. 因此, ll.size是一个int, ll.size()是“调用”该int。

Try to rename your method to something else than size and see if that works. 尝试将您的方法重命名为size以外的名称,然后查看是否可行。

You can't have both a instance variable name size and an instance method name size . 您不能同时拥有实例变量名称大小和实例方法名称大小

How would one distinguish them ? 如何区分它们?

Here the instance variable take precedence because it was define first (you probably have a self.size = x in your __init__ method and therefore appearing first in your object __dict__ ) which is a int and therefore not callable. 这里实例变量优先,因为它是首先定义的(您可能在__init__方法中具有self.size = x ,因此首先在对象__dict__出现),它是一个int ,因此不可调用。

If you have nothing special to do on the size value just use the attribute directly without defining a function: 如果您对size值没有什么特别的事情,则直接使用该属性而不定义函数:

class Foo:
        def __init__(self, somearg):
            # ...
            self.size = somearg * 3
>>> foo = Foo(3)
>>> foo.size
9

If you want to make something more complex (contrary to my trivial example here) use a property : 如果您想做更复杂的事情(与这里的琐碎示例相反),请使用属性

class Foo:
    def __init__(self, somearg):
        # ...
        self._size = None
        self._someattr = somearg
    # ...
    @property
    def size(self):
        if self._someattr > 2:
            return self._someattr * 3
        return 1
>>> foo = Foo(3)
>>> foo.size
9
>>> bar = Foo(2)
>>> bar.size
 1

To fully understand the advantage of the property decorator read this tutorial 要完全了解属性装饰器的优势,请阅读本教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM