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
#2
Hi @SpongeB0B , you could use a ChainMap to create a dictionary local to the instance
from collections import ChainMap

class CommonCar:

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

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

        self.value = value

        self.attrib = ChainMap(addattrib or {}, self.attrib)

#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 POLO wheel 4 automatic False brand VW
Alternately, you could copy the default dictionary in every instance and update the copy.
Reply
#3
(May-20-2023, 10:22 AM)Gribouillis Wrote: ... Alternately, you could copy the default dictionary in every instance and update the copy.
Thanks @Gribouillis, Yes that almost what I wanted to do initially but I don't get how to make it happen...
[Image: NfRQr9R.jpg]
Reply
#4
(May-20-2023, 11:39 AM)SpongeB0B Wrote: I don't get how to make it happen...
You can do
_attrib = {
    'wheel':4,
    'automatic':False}

class CommonCar:

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

        self.value = value
        self.attrib = dict(_attrib)
        if addattrib:
            self.attrib.update(addatrib)
You can also have a read-only dictionary in the class instead of hiding the default dictionary.
import types

class CommonCar:

    attrib = types.MappingProxyType({
        'wheel':4,
        'automatic':False}) # read-only default attributes dictionary

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

        self.value = value
        self.attrib = dict(self.attrib)
        if addattrib:
            self.attrib.update(addattrib)
SpongeB0B likes this post
Reply
#5
Thanks again @Gribouillis,

I've I read again the documentation about python classes and especially the mechanism between the
Class attributes and Instance attributes.

In my initial post I wanted to be able to compare a default dictionary inside a class definition against the same dict. but from a instance. In short compare the Class dict Vs the instance Dict.

So the easiest way (for me) is to create first an instance that will be the 'default' and all the rest of the instance will be the one to work with and to compare to the 'default one'.

Thumbs Up
[Image: NfRQr9R.jpg]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [SOLVED] [ElementTree] Grab text in attributes? Winfried 3 1,640 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,324 Mar-14-2022, 11:21 PM
Last Post: deanhystad
  Distinguishing different types of class attributes Drone4four 4 2,116 Feb-21-2022, 06:34 PM
Last Post: deanhystad
  Calls to Attributes of a Class SKarimi 3 3,408 Apr-22-2021, 04:18 PM
Last Post: SKarimi
  Listing Attributes of Objects & Classes JoeDainton123 4 2,363 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,055 May-29-2020, 12:30 PM
Last Post: KM007
  Class Instances called in the wrong order IanIous 4 2,856 Mar-06-2020, 02:16 PM
Last Post: IanIous
  SQL Alchemy dynamic class - declarative_base losing attributes mrdominikku 4 3,740 Jan-10-2020, 06:46 PM
Last Post: mrdominikku
  How to access class variable? instances vs class drSlump 5 3,359 Dec-11-2019, 06:26 PM
Last Post: Gribouillis
  Getting attributes from a list containing classes midarq 2 2,170 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