473,597 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to call module functions inside class instance functions?

Hi Everyone,

I have encountered a small problems. How to call module functions
inside class instance functions? For example, calling func1 in func2
resulted in a compiling error.

"my module here"

def func1():
print "hello"

class MyClass:
def func2():
#how can I call func1 here.
func1() #results in an error
Thanks,
Geoffrey

Aug 19 '07 #1
7 8515
On Aug 18, 5:40 pm, beginner <zyzhu2...@gmai l.comwrote:
Hi Everyone,

I have encountered a small problems. How to call module functions
inside class instance functions? For example, calling func1 in func2
resulted in a compiling error.

"my module here"

def func1():
print "hello"

class MyClass:
def func2():
#how can I call func1 here.
func1() #results in an error

Thanks,
Geoffrey
You might want to check one of the online tutorials about how to code
classes. Google or look at "Learning Python" here http://www.python-eggs.org/
def func1():
print "hello"

class MyClass:
def func2(self):
#how can I call func1 here.
func1() #results in an error

MC= MyClass()
MC.func2()

Aug 19 '07 #2
beginner wrote:
Hi Everyone,

I have encountered a small problems. How to call module functions
inside class instance functions? For example, calling func1 in func2
resulted in a compiling error.

"my module here"

def func1():
print "hello"

class MyClass:
def func2():
#how can I call func1 here.
func1() #results in an error
If you had bothered to include the error message it would have been
obvious that the problem with your code isn't in body of the method at
all - you have failed to include an argument to the method to pick up
the instance on which the method is called. I am guessing that when you
create an instance and call its func2 method you see the message

Traceback (most recent call last):
File "test07.py" , line 12, in <module>
myInstance.func 2()
TypeError: func2() takes no arguments (1 given)

which would have been a very useful clue. Please include the traceback
in future! Here's a version of your program that works.

sholden@bigboy ~/Projects/Python
$ cat test07.py
"my module here"

def func1():
print "hello"

class MyClass:
def func2(self):
#how can I call func1 here.
func1() #results in an error

myInstance = MyClass()
myInstance.func 2()

sholden@bigboy ~/Projects/Python
$ python test07.py
hello

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 19 '07 #3
beginner <zy*******@gmai l.comwrote:
I have encountered a small problems. How to call module functions
inside class instance functions? For example, calling func1 in func2
resulted in a compiling error.

"my module here"

def func1():
print "hello"

class MyClass:
def func2():
#how can I call func1 here.
func1() #results in an error
rhymes@groove ~ % cat t.py
def func1():
print "hello"

class MyClass:
def func2():
func1()
rhymes@groove ~ % python -c "import t"
rhymes@groove ~ %

As you can see there no compiling error, because the syntax is correct,
you'll eventually get a runtime error like this:
>>import t
c = t.MyClass()
c.func2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func2() takes no arguments (1 given)

That's because you left out the "self" argument in the definition of
"func2()". This version is correct:

--
def func1():
print "hello"

class MyClass(object) :
def func2(self):
func1()

c = MyClass()
c.func2()
--

rhymes@groove ~ % python tcorrect.py
hello
HTH

--
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair
Aug 19 '07 #4
On Aug 18, 8:18 pm, Steve Holden <st...@holdenwe b.comwrote:
beginner wrote:
Hi Everyone,
I have encountered a small problems. How to call module functions
inside class instance functions? For example, calling func1 in func2
resulted in a compiling error.
"my module here"
def func1():
print "hello"
class MyClass:
def func2():
#how can I call func1 here.
func1() #results in an error

If you had bothered to include the error message it would have been
obvious that the problem with your code isn't in body of the method at
all - you have failed to include an argument to the method to pick up
the instance on which the method is called. I am guessing that when you
create an instance and call its func2 method you see the message

Traceback (most recent call last):
File "test07.py" , line 12, in <module>
myInstance.func 2()
TypeError: func2() takes no arguments (1 given)

which would have been a very useful clue. Please include the traceback
in future! Here's a version of your program that works.

sholden@bigboy ~/Projects/Python
$ cat test07.py
"my module here"

def func1():
print "hello"

class MyClass:
def func2(self):
#how can I call func1 here.
func1() #results in an error

myInstance = MyClass()
myInstance.func 2()

sholden@bigboy ~/Projects/Python
$ python test07.py
hello

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------- Hide quoted text -

- Show quoted text -
I apologize for not posting the exact code and error message. The
missing "self" is due to a typo of mine. It is not really the problem
I am encountering.

testmodule.py
-----------------
"""Test Module"""

def __module_level_ func():
print "Hello"

class TestClass:
def class_level_fun c(self):
__module_level_ func()
main.py
------------------
import testmodule

x=testmodule.Te stClass()
x.class_level_f unc()
The error message I am encountering is: NameError: global name
'_TestClass__mo dule_level_func ' is not defined

I think it has something to do with the two underscores for
__module_level_ func. Maybe it has something to do with the python
implementation of the private class level functions.

By the way, the reason I am naming it __module_level_ func() is because
I'd like __module_level_ func() to be private to the module, like the C
static function. If the interpreter cannot really enforce it, at least
it is some sort of naming convention for me.

Thanks,
Geoffrey

Aug 19 '07 #5
On Aug 18, 8:13 pm, Zentrader <zentrad...@gma il.comwrote:
On Aug 18, 5:40 pm, beginner <zyzhu2...@gmai l.comwrote:


Hi Everyone,
I have encountered a small problems. How to call module functions
inside class instance functions? For example, calling func1 in func2
resulted in a compiling error.
"my module here"
def func1():
print "hello"
class MyClass:
def func2():
#how can I call func1 here.
func1() #results in an error
Thanks,
Geoffrey

You might want to check one of the online tutorials about how to code
classes. Google or look at "Learning Python" herehttp://www.python-eggs.org/
def func1():
print "hello"

class MyClass:
def func2(self):
#how can I call func1 here.
func1() #results in an error

MC= MyClass()
MC.func2()- Hide quoted text -

- Show quoted text -
Thanks for your help. The missing "self" is a typo of mine. It is not
the problem I am encountering. Sorry for posting the wrong code.

Aug 19 '07 #6
By the way, the reason I am naming it __module_level_ func() is because
I'd like __module_level_ func() to be private to the module, like the C
static function. If the interpreter cannot really enforce it, at least
it is some sort of naming convention for me.
re the above: set file permissions for testmodule.py to limit access.
IMHO it is a better solution.

Aug 19 '07 #7
beginner <zy*******@gmai l.comwrote:
...
testmodule.py
-----------------
"""Test Module"""

def __module_level_ func():
print "Hello"

class TestClass:
def class_level_fun c(self):
__module_level_ func()
main.py
------------------
import testmodule

x=testmodule.Te stClass()
x.class_level_f unc()
The error message I am encountering is: NameError: global name
'_TestClass__mo dule_level_func ' is not defined

I think it has something to do with the two underscores for
__module_level_ func. Maybe it has something to do with the python
implementation of the private class level functions.

By the way, the reason I am naming it __module_level_ func() is because
I'd like __module_level_ func() to be private to the module, like the C
static function. If the interpreter cannot really enforce it, at least
it is some sort of naming convention for me.
The two underscores are exactly the cause of your problem: as you see in
the error message, the compiled has inserted the CLASS name (not MODULE
name) implicitly there. This "name mangling" is part of Python's rules.

Use a SINGLE leading underscore (NOT double ones) as the "sort of naming
convention" to indicate privacy, and Python will support you (mostly by
social convention, but a little bit technically, too); use a different
convention (particularly one that fights against the language rules;-)
and you're "fighting city hall" to no good purpose and without much hope
of achieving anything whatsoever thereby.
Alex
Aug 19 '07 #8

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

Similar topics

1
1216
by: Jacob H | last post by:
Hello all, I would like to be able to take a module full of class instances, functions, etc and bind all its names to a separate container class in a different module. I have come up with the following way to do it.. (module "globals") class Container: pass
2
1530
by: Ray | last post by:
Greeting, I'm still grasping the class concept so bear with me. I have a vb.net app in which I wrote and placed various public functions for later reference. In vb.net there is an option to "add class" or "add module". My understanding is a module is a class so what is the difference? Correct me if I'm wrong....a module allows you to call various functions/procedures without first defining and class you do?
8
5715
by: meendar | last post by:
what will a object of an Empty class( contain nothing), do on default.What are all the default methods it calls. what is the use of creating the object for an empty class?
4
1647
by: Ritesh Raj Sarraf | last post by:
Hi, I have a class defined in a file called foo.py In bar.py I've imported foo.py In bar.py's main function, I instantiate the class as follows: log = foo.log(x, y, z) Now in main I'm able to use log.view(), log.error() et cetera.
6
4021
by: JonathanOrlev | last post by:
Hello everyone, I have a newbe question: In Access (2003) VBA, what is the difference between a Module and a Class Module in the VBA development environment? If I remember correctly, new types of objects (classes) can only be defined in Class modules.
12
4078
by: Andy Terrel | last post by:
Okay does anyone know how to decorate class member functions? The following code gives me an error: Traceback (most recent call last): File "decorators2.py", line 33, in <module> s.update() File "decorators2.py", line 13, in __call__ retval = self.fn.__call__(*args,**kws) TypeError: update() takes exactly 1 argument (0 given)
1
1483
by: Bryan Parkoff | last post by:
I am able to create pointer to function variable as 's2'. m_func1() function's memory address is copied into s2 variable. Then s2 acts like pointer to function and is executed without any problem. I do not want function's memory address to be copied into s2 at run-time. How can I define at static time? Here is a code below. Notice comment after static const pmfn1 s2. class Testpm {
3
2068
by: wendallsan | last post by:
Hi All, I've stumped myself writing an app that uses Prototype and a bit of PHP. Here is what I have: I have a custom class named Default_county_init_data that, upon initialization makes several Ajax.Request calls to gather data from the server. What I'm having trouble with is getting the data from the Ajax call back to the custom class instance. I basicially want to get a Javascript array from my PHP page and insert that into the...
5
1885
emaghero
by: emaghero | last post by:
I have the following class declaration class class_name{ public: class_name(); // Constructor // Member functions void function_1(); void function_2(double *mat); void function_3();
0
7971
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8276
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8381
jinu1996
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8259
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6698
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5436
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3889
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2408
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1243
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.