Python Forum
[solved] Classes, assign an attributes to a class not to instances..
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[solved] Classes, assign an attributes to a class not to instances..
#1
Question 
Hi everyone,

I would like to create a class with a default dictionary attribute.
and when being Instantiated I would like to add (or not) some items to that attribute (attrib in the following example)


class CommonCar:

	attrib = {
		'wheel':4,
		'automatic':False}

	def __init__(self, addattrib=None, value=1):

		self.value = value

		if addattrib != None:
			self.attrib |= addattrib

#instantiation
polo = CommonCar({'brand':'VW'})


#Check the items inside the class CommonCar
print('CommonCar'.upper())
for k,v in CommonCar.attrib.items():
	print(k, v)

#Check the items inside [inline]attrib[/inline]
print('\npolo'.upper())
for k,v in polo.attrib.items():
	print(k, v)
Output:
COMMONCAR wheel 4 automatic False brand VW #<-------------- (should not have this item!!) POLO wheel 4 automatic False brand VW
So the output is unexpected, because the class COMMONCAR get also the merge dict. of the instantiation of polo

Any ideas ?

Thanks
[Image: NfRQr9R.jpg]
Reply


Messages In This Thread
[solved] Classes, assign an attributes to a class not to instances.. - by SpongeB0B - May-20-2023, 09:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] [ElementTree] Grab text in attributes? Winfried 3 1,660 May-27-2022, 04:59 PM
Last Post: Winfried
  [Solved] Novice question to OOP: can a method of class A access attributes of class B BigMan 1 1,350 Mar-14-2022, 11:21 PM
Last Post: deanhystad
  Distinguishing different types of class attributes Drone4four 4 2,138 Feb-21-2022, 06:34 PM
Last Post: deanhystad
  Calls to Attributes of a Class SKarimi 3 3,442 Apr-22-2021, 04:18 PM
Last Post: SKarimi
  Listing Attributes of Objects & Classes JoeDainton123 4 2,380 Aug-28-2020, 05:27 AM
Last Post: ndc85430
  How to create a varying qty of instances of a Class and name them? KM007 2 2,076 May-29-2020, 12:30 PM
Last Post: KM007
  Class Instances called in the wrong order IanIous 4 2,884 Mar-06-2020, 02:16 PM
Last Post: IanIous
  SQL Alchemy dynamic class - declarative_base losing attributes mrdominikku 4 3,770 Jan-10-2020, 06:46 PM
Last Post: mrdominikku
  How to access class variable? instances vs class drSlump 5 3,400 Dec-11-2019, 06:26 PM
Last Post: Gribouillis
  Getting attributes from a list containing classes midarq 2 2,190 Dec-03-2019, 12:42 AM
Last Post: midarq

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020