Difference between methods and attributes in python

后端 未结 5 441
渐次进展
渐次进展 2020-12-15 13:09

I am learning python and doing an exercise about classes. It tells me to add nd attribute to my class and a method to my class. I always thought these were the same thing un

5条回答
  •  别那么骄傲
    2020-12-15 13:36

    class example:
        global a
        # a=0
    
        def __init__(self,x,y):
            self.fname=x
            self.lname=y
        def show(self):
            return "first name: {} & Last name: {}".format(self.fname,self.lname)
    
    obj1=example('reyan','ishtiaq')
    obj2=example('ishtiaq','reyan')
    
    print('method associated with obj1: '+ obj1.show())
    print('method associated with obj2: '+ obj2.show())
    
    obj1.a=20
    obj2.a=30
    
    print(obj1.a)
    print(obj2.a)
    

    output: method associated with obj1: first name: reyan & Last name: ishtiaq................ method associated with obj2: first name: ishtiaq & Last name: reyan................ 20 30

提交回复
热议问题