bartonc 6,596
Recognized Expert Expert
Still have to prepend "default" when assigning variables to this class, but it now allows val = inst.vaule: - """Encapuslate a Default Values Object and Config File"""
-
-
from inspect import getmembers
-
import wx
-
-
class DefaultValueHolder(object):
-
"""Intended for use with wxConfig (or maybe _winreg) to set up and/or get
-
registry key names and values. Name attrs as default*. "default"
-
will be stripped of when reading and writing to the config file.
-
You may not use the name varDict as one of the variable names."""
-
-
def __init__(self, appName, grpName):
-
"""Open or create the application key"""
-
self.appName = appName
-
self.grpName = grpName # if the key or group doesn't exit, it will be created
-
self.config = wx.Config(appName) # Open the file (HKCU in windows registry)
-
-
def __getattribute__(self, name):
-
try:
-
return object.__getattribute__(self, "default%s" %name)
-
except AttributeError:
-
return object.__getattribute__(self, name)
-
-
def GetVariables(self):
-
return [{"name":var[0][7:], "value":var[1], "type":type(var[1])}
-
for var in getmembers(self) if var[0].startswith('default')]
-
-
def SetVariables(self, varDict={}, **kwargs):
-
kwargs.update(varDict)
-
for name, value in kwargs.items():
-
setattr(self, "default%s" %name, value)
-
-
def InitFromConfig(self):
-
config = self.config
-
group = self.grpName
-
-
if not config.Exists(group):
-
self.WriteRegistryGroup(group)
-
-
else:
-
config.SetPath(group)
-
for var in self.GetVariables():
-
name = var['name']
-
if config.Exists(name):
-
value = self.ReadRegistry(name, var['type'])
-
self.SetVariables({name:value})
-
else:
-
self.WriteRegistry(name, var['value'], var['type'])
-
config.SetPath("")
-
-
def WriteRegistryGroup(self, group):
-
self.config.SetPath(group)
-
for var in self.GetVariables():
-
self.WriteRegistry(var['name'], var['value'], var['type'])
-
self.config.SetPath("")
-
-
def UpdateConfig(self):
-
self.WriteRegistryGroup(self.grpName)
-
-
def ReadRegistry(self, name, type):
-
value = None
-
if type == str:
-
value = self.config.Read(name)
-
elif type in (int, long):
-
value = self.config.ReadInt(name)
-
elif type == float:
-
value = self.config.ReadFloat(name)
-
return value
-
-
def WriteRegistry(self, name, value, type):
-
if type == str:
-
self.config.Write(name, value)
-
elif type in (int, long):
-
self.config.WriteInt(name, value)
-
elif type == float:
-
self.config.WriteFloat(name, value)
-
-
-
if __name__ == "__main__":
-
## class SetSelfFromDefaults(object):
-
## def __init__(self):
-
## self.test = test = DefaultValueHolder("HETAP Pro 2.00", "Database")
-
## test.SetVariables(UserName="peter", Password="pan", ServerName="MyServer", database="")
-
## test.InitFromConfig()
-
##
-
## self.SetupLoginVars(test)
-
##
-
## def SetupLoginVars(self, defaultHolder):
-
## """Cool tricks, use somewhere, someday."""
-
## for var in defaultHolder.GetVariables():
-
## execStr = "self.%s = %s" %(var['name'], (repr(var['value']), var['value'])[var['type'] != str])
-
## exec(execStr) in locals()
-
##
-
## testClass = SetSelfFromDefaults()
-
## print testClass.UserName
-
-
test = DefaultValueHolder("HETAP Pro 2.00", "Database")
-
test.SetVariables(UserName = "peter", Password = "pan", ServerName = "MyServer", database="")
-
test.InitFromConfig()
-
print test.UserName
-
test.defaultvar1=77
-
print test.GetVariables()
-
#### this also works:
-
## test.defaultUserName = "joe"
1 5697 bartonc 6,596
Recognized Expert Expert
I cleaned this up too: -
-
def GetVariables(self):
-
return [{"name":name[7:], "value":value, "type":type(value)}
-
for name, value in getmembers(self) if name.startswith('default')]
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Ruud de Jong |
last post by:
I have the situation where I need to construct the name
of a static method, and then retrieve the corresponding
function from a class object.
I thought I could just use __getattribute__ for this purpose.
This works fine if I already have an instantiation of the class,
but not when I try this on the class object directly.
A bare bones...
|
by: Daniel Schüle |
last post by:
Hello NG
is this kind of usage possible for classes
l =
l.__getattribute__("count")(1)
for example
f = foo()
def bar(t, m, p):
|
by: Gigi |
last post by:
Hi,
In the Python documentation regarding __getattribute__ (more attribute
access for new style classes) it is mentioned that if __getattribute__
is defined __getattr__ will never be called (unless called explicitely).
Here is the exact citation:
"""
The following methods only apply to new-style classes.
__getattribute__( self, name)
|
by: Sylvain Ferriol |
last post by:
hello
when i define __getattribute__ in a class, it is for the class instances
but if i want to have a __getattribute__ for class attributes
how can i do that ?
sylvain
|
by: Stefan Sonnenberg-Carstens |
last post by:
Hi there,
I'm facing some strange things - but maybe only me is strange - anyway...
i wrote the following code:
+++
class T(object):
def __init__(self,name='',port=80):
self.name=name
| |
by: Barry Kelly |
last post by:
I'm running this version of Python:
Python 2.4.3 (#1, May 18 2006, 07:40:45)
on cygwin
I read in the documentation that these two expressions are
interchangeable:
x.__getattribute__('name') <==> x.name
|
by: Pedro Werneck |
last post by:
Hi all
I noticed something strange here while explaining decorators to someone.
Not any real use code, but I think it's worth mentioning.
When I access a class attribute, on a class with a custom metaclass with
a __getattribute__ method, the method is used when acessing some
attribute directly with the class object, but not when you do...
|
by: Adam Donahue |
last post by:
As an exercise I'm attempting to write a metaclass that causes an
exception to be thrown whenever a user tries to access
'attributes' (in the traditional sense) via a direct reference.
Consider:
class X( object ):
y = 'private value'
def get_y( self ): return self.y
|
by: bukzor |
last post by:
I want to make a MixIn class that waits to initialize its super-
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have. I've commented out
the "delattr" call because it throws an AttributeError (although I...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |