Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using color in python
#11
(Sep-22-2019, 10:54 PM)Windspar Wrote: You can always wrap it.

Can we also have a dictionary type property facilitating access to all existing pairs of ColorNames & ColorValues in one statement?
A.D.Tejpal
Reply
#12
Is this what you are talking about.
import pygame

class PygameColors:
    def __init__(self):
        self.__dict__.update(pygame.color.THECOLORS)

    def __getitem__(self, key):
        return self.__dict__[key]

    def add(self, name, r, g, b, a=255):
        if name not in vars(self).keys():
            setattr(self, name, pygame.Color(r, g, b, a))
        else:
            print("Color already exists:", name)

color = PygameColors()

print("white:", color["white"], color.white, pygame.Color("white"))
99 percent of computer problems exists between chair and keyboard.
Reply
#13
(Sep-23-2019, 10:27 PM)Windspar Wrote: Is this what you are talking about.

I meant contents of the inbuilt color dictionary. Adding function colordict(), to the code provided by you, has met this requirement, as placed below:

import pygame
 
class PygameColors:
    def __init__(self):
        self.__dict__.update(pygame.color.THECOLORS)
 
    def __getitem__(self, key):
        return self.__dict__[key]
 
    def add(self, name, r, g, b, a=255):
        if name not in vars(self).keys():
            setattr(self, name, pygame.Color(r, g, b, a))
        else:
            print("Color already exists:", name)

    def colordict(self):
        return self.__dict__
 
color = PygameColors()
print(color.colordict())
A.D.Tejpal
Reply
#14
Why not just print it out this way
print(color.__dict__)
Reply
#15
(Sep-28-2019, 04:09 PM)SheeppOSU Wrote: Why not just print it out this way

That is simplest. Thanks.

It might also be desirable to avoid naming a user created object as "color" as that happens to be the name of a built-in object in pygame (imported into the class in question).
A.D.Tejpal
Reply
#16
You can also do this.
print(vars(color))
99 percent of computer problems exists between chair and keyboard.
Reply
#17
(Sep-30-2019, 10:39 AM)Windspar Wrote: You can also do this.

Very Nice. Thanks.
A.D.Tejpal
Reply


Forum Jump:

User Panel Messages

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