-1

If x is an object in whose class the method "--call--" is defined, we can call x() directly to execute the method "--call--". Is there a method like "--call--" via which I call x directly to get the value of an attribute of x ? Thanks

shuairenqin
  • 103
  • 1
  • 8
  • Possible duplicate of [Python \_\_call\_\_ special method practical example](https://stackoverflow.com/questions/5824881/python-call-special-method-practical-example) – Mayur Vora Jul 07 '17 at 06:32
  • Thank you for your answer. I know the functionality of --call--. I want to know whether or not there is a method like --call-- via which I call x directly without adding .something to get the value of an attribute of x, i.e. x.somthing. – shuairenqin Jul 07 '17 at 06:45
  • I understand your question. But when you ask a question so give the example of the code what you want and give the proper name of the class because any user read your question so give downvote. I suggest putting the best question. – Mayur Vora Jul 07 '17 at 06:49
  • thank you for you suggestions. – shuairenqin Jul 07 '17 at 06:51
  • No, there isn't. – juanpa.arrivillaga Jul 07 '17 at 07:09
  • I don't quite understand the question. What attribute do you expect and what is your "call x directly"? `__call__` is an example of a [special method name](https://docs.python.org/3/reference/datamodel.html#special-method-names) to implement an operator, like `__getitem__` or `__sub__`. `.` can pretty much be implemented with `__getattr__`, and there's a [`getattr()`](https://docs.python.org/3/library/functions.html#getattr) function for looking up attributes by runtime names. – Yann Vernier Jul 07 '17 at 09:45

1 Answers1

0

Hello shuairenqin,

You can access the class attribute using object or instance using python several inbuilt method like,

1. object.getitem(self, key)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the getitem() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.

For Example,

class Library:
    def __init__(self):
         self.books = { 'title' : 1, 'title2' : 2, 'title3' : 2 }
    def __getitem__(self, i):
             return self.books[i]
    def __iter__(self): 
        return self.books.itervalues()

librarya = Library()
print librarya['title']

2. object.call(self[, args...])

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.call(arg1, arg2, ...).

For Example,

class Animal(object):
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        self.stomach = []        

    def __call__(self,food):
        self.stomach.append(food)

    def poop(self):
        if len(self.stomach) > 0:
            return self.stomach.pop(0)

    def __str__(self):        
        return 'A animal named %s' % (self.name)       

cow = Animal('king', 4)  #We make a cow
dog = Animal('flopp', 4) #We can make many animals
print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
print cow  #here __str__ metod work

#We give food to cow
cow('gras')
print cow.stomach

#We give food to dog
dog('bone')
dog('beef')
print dog.stomach

#What comes inn most come out
print cow.poop()
print cow.stomach  #Empty stomach

print cow
'''-->output
We have 2 animales a cow name king and dog named flopp,both have 4 legs
A animal named king
['gras']
['bone', 'beef']
gras
[]
'''

3. object.getattr(self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism, getattr() is not called. (This is an intentional asymmetry between getattr() and setattr().) This is done both for efficiency reasons and because otherwise getattr() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the getattribute() method below for a way to actually get total control in new-style classes.

For Example,

class MyClass(object):

    def __init__(self):
        self.data = {'name1': 'Vora Mayur', 'name2': 'Vora Mihir'}

    def __getattr__(self, attr):
        return self.data[attr]

obj = MyClass()
print obj.name1
Mayur Vora
  • 922
  • 2
  • 14
  • 25