Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Instant Objects Method Arguments

The use of setattr and the __init__ function :]

Hi. i just want to be sure that i understand this topic.

the __init__ function is like a constrcutor in c# or java?, with the __init__ we define what attributes the Object need to have to be an Object.

for example:

public Car(int num_of_wheel, string carCompany)
{
  this.num_of_wheel = num_of_wheel
 this.carCompany  = "Treehouse"

}

is the same as:

class Porfile
      def __init__(self,name, coding_is_fun = True, **kwargs):
         self.name = "bot.net"
         self.coding_is_fun = coding_is_fun

They both do the same thing, in order to be a Profile Object i need to at least have a "name" and coding_is_fun, and ton be a Car Object i need to atleast state the num of wheel and the car company to be an Car Object.

The only difference is that in python, unlike in c# or java, if i want to add other attributes after i already defined what are the requirements to be the Object, i can use the setattr() function which let me add other attributes to the Object instead of initialize them in the __init__ function evrey single time.

i loop trough the kwargs dict in order to "insert" the bonus attributes into a dict? setattr(self, key, value) for example it's like self = an instance of the Thief class key = the name of the attr and the value is the value. so:

bot = Thief()
setattr(bot,key,value) = bot.name = "bot.net"

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

You have it correct. The built-in setattr function takes an instance and sets the attribute "key" to the value "value".

In your code above, the bot label is point to the exact same thing as the self label within the method bot.__init__. So inside __init__ or outside of the instance, the setattr function behaves the same.

Post back if you need more help. Good luck!!