Don't understand this TypeError: 'list' object is not callable

前端 未结 2 650
轻奢々
轻奢々 2021-01-27 15:47

I have file called im.py which contains a couple of functions and several classes. The first function and class are failing with

TypeError: \'list\'         


        
相关标签:
2条回答
  • 2021-01-27 16:28

    You cannot use the same name for both a method and an attribute; methods are just special kinds of attributes. Your class may have a user() method, but by setting the attribute user on the instance, Python will find that instead of the method when you try to access b.user:

    >>> type(b.user)  # no call, just the attribute
    <class 'list'>
    

    You'll have to rename either the method or the attribute to not conflict. You could use a leading underscore for the list attribute, for example:

    class FirstClass:
        def setdata_user(self):
            self._user = getdata_user()    
        def displaydata_user(self):
            print(self._user)
        def user(self):
            u = self._user[0]
            return u
        def gids(self):
            g = self._user[1]
            return g
        def home(self):
            h = self._user[2]
            return h
    
    0 讨论(0)
  • 2021-01-27 16:43

    Python is not like some other languages where fields and methods can share the same name (such as Java). In Python when you give an instance attribute the same name as a method, the method is hidden by the attribute.

    However, in general python eschews getters and setters as they do not provide the same benefits in Python as they do in statically typed languages (such as Java).

    In Python, you would be more likely to do something like:

    class FirstClass:
        def setdata_user(self):
            data = getdata_user()
            self.user = data[0]
            self.gids = data[1]
            self.home = data[2]
            # or more simply
            self.user, self.gids, self.home = getdata_user()
    
        def displaydata_user(self):
            print([self.user, self.gids, self.home])
    
    obj = FirstClass()
    obj.setdata_user()
    obj.displaydata_user()
    # accessing individual attributes
    print("user:", obj.user)
    print("gids:", obj.gids)
    print("home:", obj.home)
    
    0 讨论(0)
提交回复
热议问题