-2

What kind of mechanism is behind this?

For example, I can define a class

class test:
    string_a="aaa"

then I can setup a instance for class test.

test_instance=test()

later I can assign a test_attr to test_instance.

test_instance.test_attr="bbb"
print test_instance.test_attr

this will print, "bbb"

so what is behavior for? anything conflict to __init__?

Thanks.

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
Bing
  • 378
  • 1
  • 3
  • 15
  • Does this means if don't need to make a subclass to represent some special instance case, then I can just append private attributes to the class instance I want to use? so this is good? – Bing May 06 '15 at 12:29
  • Just learn more from this [link](https://stackoverflow.com/questions/27257379/class-attributes-in-python) by abarnert, (pythonic, setter, getter) – Bing May 06 '15 at 13:04
  • It's not clear what you want, but Python doesn't really *have* "private attributes". Just because you *can* add arbitrary attributes, doesn't mean that doing so is a good idea. – jonrsharpe May 06 '15 at 13:05
  • I think I am confused by the setter, getter way to give attributes value, I was trying to find a good way to set value(but not sure how python does this), just like the \@synthesize in objective C. Now it is much clear now, after read post from abarnert @jonrsharpe, thanks anyway. – Bing May 06 '15 at 13:13

1 Answers1

0

There are two things going on here:

  1. Class attributes
  2. Instance attributes

It is important to distinguish the difference.

Class Attributes as in:

class A:
    a = 1

will persist with every Instance created. That is:

a = A()
b = A()
a.a == b.a  # True

Instance Attributes are typically accessed by magic methods called __setattr__ (to set them) and __getattr__ (to retrieve them).

All instances of classes (unless you use __slots__) have an internal dict called __dict__. You don't have to "declare" attributes on a class in order to set them on an instance.

Have a read of Python Data Model

chepner
  • 497,756
  • 71
  • 530
  • 681
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • thanks, I know class Attributes is common attributes to all its instances, like string_a. And test_attr is unique to test_instance only. What I am not sure is how to organize them in a good manner when I starting define class, is there any rule to follow? – Bing May 06 '15 at 12:24
  • There are lots of opinions as well as best practices. Typically you want to model your objects/classes after some kind of representation of the data and attributes you are mutating and their desired behaviours. – James Mills May 06 '15 at 12:26
  • And also how to track this kind of unique(private) attributes? I often get lost when using python IDE to check them, and read class doc. – Bing May 06 '15 at 12:26