473,547 Members | 2,638 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question on creating class

wcc
Hello,

How do I create a class using a variable as the class name?

For example, in the code below, I'd like replace the line

class TestClass(objec t):
with something like
class eval(className) (object):

Is it possible? Thanks for your help.

className = "TestClass"

class TestClass(objec t):
def __init__(self):
print "Creating object of TestClass..."

def method1(self):
print "This is a method."

if __name__ == "__main__":
o = TestClass()
o.method1()

--
wcc

Jan 4 '07 #1
6 1773
You can always rename your defined clas afterwards

class TestClass:
pass

myClass = TestClass

--
Tõnis

On Jan 4, 9:27 am, "wcc" <wcc...@gmail.c omwrote:
Hello,

How do I create a class using a variable as the class name?

For example, in the code below, I'd like replace the line

class TestClass(objec t):
with something like
class eval(className) (object):

Is it possible? Thanks for your help.

className = "TestClass"

class TestClass(objec t):
def __init__(self):
print "Creating object of TestClass..."

def method1(self):
print "This is a method."

if __name__ == "__main__":
o = TestClass()
o.method1()

--
wcc
Jan 4 '07 #2
Or if you have required class name in variable, then use:

class TestClass:
pass

globals()[className] = TestClass

--
Tõnis

On Jan 4, 9:27 am, "wcc" <wcc...@gmail.c omwrote:
Hello,

How do I create a class using a variable as the class name?

For example, in the code below, I'd like replace the line

class TestClass(objec t):
with something like
class eval(className) (object):

Is it possible? Thanks for your help.

className = "TestClass"

class TestClass(objec t):
def __init__(self):
print "Creating object of TestClass..."

def method1(self):
print "This is a method."

if __name__ == "__main__":
o = TestClass()
o.method1()

--
wcc
Jan 4 '07 #3
wcc schrieb:
Hello,

How do I create a class using a variable as the class name?

For example, in the code below, I'd like replace the line

class TestClass(objec t):
with something like
class eval(className) (object):

Is it possible? Thanks for your help.

className = "TestClass"

class TestClass(objec t):
def __init__(self):
print "Creating object of TestClass..."

def method1(self):
print "This is a method."

if __name__ == "__main__":
o = TestClass()
o.method1()

--
wcc
You call 'type' to create a new-style class. The signature is:
"type(name, bases, dict) -a new type".
>>def __init__(self):
.... print "Creating object of TestClass..."
....
>>def method1(self):
.... print "This is a method"
....
>>TestClass = type("TestClass ", (), {"__init__": __init__, "method1": method1})
help(TestClas s)
Help on class TestClass in module __main__:

class TestClass(__bui ltin__.object)
| Methods defined here:
|
| __init__(self)
|
| method1(self)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'TestClass' objects>
| list of weak references to the object (if defined)
>>TestClass()
Creating object of TestClass...
<__main__.TestC lass object at 0x00AED0B0>
>>TestClass().m ethod1()
Creating object of TestClass...
This is a method
>>>

Thomas

Jan 4 '07 #4
wcc kirjoitti:
Hello,

How do I create a class using a variable as the class name?

For example, in the code below, I'd like replace the line

class TestClass(objec t):
with something like
class eval(className) (object):

Is it possible? Thanks for your help.

className = "TestClass"

class TestClass(objec t):
def __init__(self):
print "Creating object of TestClass..."

def method1(self):
print "This is a method."

if __name__ == "__main__":
o = TestClass()
o.method1()

--
wcc
I'm curious: what is the original problem that you are trying to solve?

The following works, but note that I'm no Python expert and if any of
the regular wizards around here says that doing these kind of things is
sick, I'm gonna agree 100% ;)

className = "TestClass2 "

class TestClass(objec t):
def __init__(self):
print "Creating object of TestClass..."

def method1(self):
print "This is a method."

exec('class ' + className +
'''(object):
def __init__(self):
print "Creating object of TestClass2..."

def method1(self):
print "This is a method1 of TestClass2."
''')

if __name__ == "__main__":
o = TestClass()
o.method1()
o2 = TestClass2()
o2.method1()
o2 = locals()[className]()
o2.method1()
Jan 4 '07 #5
On Wed, 03 Jan 2007 23:27:57 -0800, wcc wrote:
Hello,

How do I create a class using a variable as the class name?
Try a "class factory".

def create_class(cl assname):
class Klass(object):
def __init__(self):
print "Creating object of %s..." % self.__class__. __name__
def method(self):
print "This is a method."
k = Klass
k.__name__ = classname
return k

>>K = create_class("T estClass")
obj = K()
Creating object of TestClass...

--
Steven.

Jan 4 '07 #6
wcc
Thanks for all replies. I'll just to have to figure our which suggested
method I should use. To answer Jussi's question, this is why I asked
the question. I have the book by Mark: Python Programming on Win32.
In Charpter 12: Advanced Python and COM there is a sample code named:
DynamicPolicy.p y. It can be used to expose all methods from a python
module to a COM server which can be accessed later from other
languages, say VBA. It works great. There are quite a few modules that
I want to implement a COM server for. One of the step to create the
COM server is to define a class. Instead of revising this code for
each module, I wondered if I can create mutilple COM servers in one
program. I'll pass a module name and the corresponding class name to
some function (to be written), and the class will be created. Btw, I'm
novice to all this, hopefully my explanation isn't way off. Thank to
all again.

--
wcc

Jan 4 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2964
by: Hal Vaughan | last post by:
I think a lot of this is definately a question of personal programming style, but I'm new to Java and would like to hear a few opinions. I'm writing a control panel for an application that runs separately. The control panel is basically (almost) fully self contained. It consists of a tabbed pane with 5 different tabs. Each tab has a...
5
1248
by: Roger Bonine | last post by:
I'm working on a rewrite of our employee database. I plan to implement a fairly heavyweight base class, which includes 20 or 30 fields, including address and phone number collections and the like. (I'll use lazy init to fill the collections when needed.) More specialized employee types would inherit from the base class. Sometimes,...
55
4617
by: Steve Jorgensen | last post by:
In a recent thread, RKC (correctly, I believe), took issue with my use of multiple parameters in a Property Let procedure to pass dimensional arguments on the basis that, although it works, it's not obvious how the code works if you don't know the intricacies of the Property Let/Get syntax. Likewise, I dislike (and code to minimize the use...
2
13042
by: JS | last post by:
I'm trying to create a data layer and having problems returning a DataSet from my code that's in a class module. Please forgive me. I'm new to C# (VB'er). I decided to create my data layer in small steps. Right now, I'm just trying to attach a ComboBox to a dataset that's in my class module. In the class, I call a Stored Procedure. I know...
14
3115
by: 42 | last post by:
Hi, Stupid question: I keep bumping into the desire to create classes and properties with the same name and the current favored naming conventions aren't automatically differentiating them... (both are "Pascal Case" with no leading or trailing qualifiers). For example... I'll be modelling something, e.g. a computer, and I'll
4
274
by: Rob Meade | last post by:
Hi all, I've been writing some .net classes at work now for a while and was feeling confident in my approach - until I attended a MS ASP.Net course! :o) Before the course, if I was going to create perhaps something that needed an "item" object, and also a collection of those items, I'd write 2 classes, the first for the individual items,...
12
1293
by: RSH | last post by:
I am still trying to grasp the use of real world Objects and how to conceptualize them using a business scenerio. What I have below is an outline that I am wrestling with trying to figure out a class structure:\ Top level Objects: Companies Employees
8
328
by: RSH | last post by:
Hi, I am working on some general OOP constructs and I was wondering if I could get some guidance. I have an instance where I have a Base Abstract Class, and 4 Derived classes. I now need to make a list class that will store the objects. My question is how do I go about creating the list class...I am assuming it should be a standalone...
20
4011
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. ...
0
7510
marktang
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...
0
7437
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...
0
7703
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7463
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...
0
7797
tracyyun
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...
0
6032
agi2029
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...
1
5362
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3493
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...
0
748
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.