[Tutor] How to set variables inside a class()

Reuben reuben.dlink at gmail.com
Tue Nov 26 11:57:57 CET 2013


Yes! I got my answer now. Thanks all

@Dominick: sorry about my explanation.
On 26-Nov-2013 4:24 PM, "Alan Gauld" <alan.gauld at btinternet.com> wrote:

> On 26/11/13 07:30, Reuben wrote:
>
>> Hi,
>>
>> Following is my code:
>> #############################################
>> class Animal():
>>
>>        flag = True
>>        print flag
>>
>>        def __init__(self,name):
>> self.name <http://self.name> = name
>>             print self.name <http://self.name>
>>
>>        def walk(self):
>>            print "I am walking"
>>
>>
>> if __name__ == '__main__':
>>       test = Animal('boxer')
>>       test.flag = False
>>
>
>
> If you really want the flag to be a class attribute rather than an
> instance one you should set it using the class name. So instead of
> test.flag use
>         Animal.flag = False
>
> That works inside the class methods too.
>
> By setting test.flag you are creating a new instance level attribute
> that exists only within the test instance. That's legal Python
> but usually its not a good idea to have different instances of
> the same class having different attributes.
>
> >>> class C:
> ...    f = True
> ...    def g(self): self.f = 42
> ...
> >>> c = C()
> >>> c.f
> True
> >>> c.g()
> >>> c.f
> 42
> >>> C.f
> True
> >>> d = C()
> >>> d.f = 66
> >>> d.f
> 66
> >>> C.f
> True
> >>>
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131126/21aa1273/attachment.html>


More information about the Tutor mailing list