Why does a class get "called" when not initiated? - Python - python

For example, in the following code:
class test:
print "Hi"
Python would automatically print 'hi'. Sorry if this is an obvious question, but I can't find out why Python would do that unless a 'test' object was initiated.
* I just started programming in general a few months ago and Python is my first language, so please spare some mercy on me.

You are building a class; the body of a class is executed as a function to build the definition. The local namespace of that 'function' forms the set of attributes that make up the class. See the class statement documentation.
Methods in the class body are not executed; like function definitions, you need to call them first. But if you didn't first call the class body, you don't know what methods the class has, at all.
In the same way, any top-level code in a module is executed when you import a module, to form the module namespace. If you put print "Hi" in a module, it is also executed immediately.

Related

How do I take functions that I already made to run a program and put them under a class?

I am making a contact list system for a class project and used tkinter to make my gui and sqlite3 for the database. I made a bunch of methods that have basically solved the problem but I noticed the question paper says that the functions need to be in a class. How do I put these functions under a class without messing everything up. I am using python3.
A function in a module is similar to a static method in a class. Without knowing any of your app's specifics:
If you have a function that does what you want
def f():
return 'g'
and you want to encapsulate it in a class
class Q:
pass
just assign it as a static method to that class
Q.f = staticmethod(f)
Whenever you need to use that function you have to call it via the class
>>> Q.f()
g
This is similar to what happens when you import a module that has functions - you import the module and call the functions using the module name (the functions are module attributes) - modulename.func().
I really have no idea how this fits with your need or what any downsides might be.

python, how to detect attributes or functions that defined in class but never called by the instance of class?

As you know, when the project's code is very large and there are so many attributes and functions defined in a Class, but some of them never be called by the instance of the Class, and maybe some of them has been discarded. Here is a example:
class Foo(object):
""""""
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
...
self.y = 25
self.z = 26
def func1(self):
pass
def func2(self):
pass
def func3(self):
pass
...
...
def func100(self):
pass
if __name__ == '__main__':
f = Foo()
f.func1()
f.func2()
print f.a, f.b, f.z
In the above code, the instance f of class Foo just called func1() and func2(). And how to find all the attributes and functions of class that never called by the instance of class.
I have tried compiler module but that could not solve my question. And dir(my_instance) is just print all the functions and attributes defined the the class.
Thanks in advance.
You can try coverage.py. It's not static analysis, but actually runs your code and records which statements are executed, outputting annotated html or txt as you wish (quite nicely formatted as well). You can then look for functions and methods whose bodies are not executed at all.
This still doesn't take care of unused attributes. And I don't know the answer to that. Maybe comment them out one at a time and see if tests still pass...
It's pretty hard to prove something is or is not used in the general case. Python is a dynamic language; if even one bit of code calls into code the static analyzer doesn't fully analyze, it could be accessing the variables mentioned.
The pylint and flake8 tools will tell you about local and global names that aren't defined prior to use (unless you break them by using from x import * style imports), and about imports that are never used (an import that is never used is usually wrong, but even then, it could be an intentional part of the interface, where linters would have to be silenced), but I don't believe they can tell you that a given attribute is never accessed; after all, someone else could import your module and access said attributes.
Use the profile module in the standard library.
python -m cProfile -o output_file myscript.py
Then load the stats file and use print_callees() to get all the functions that were called--during that run of the program.
I don't know of any easy way to find out which attributes are used.

Why does this class run?

I've been playing with my codes a little for a while, and this one is not about a bug or anything, but i just don't understand why class main() runs without needing to initialize it...
class vars():
var1 = "Universe!"
var2 = "Oscar!"
var3 = "Rainbow!"
class main():
print (vars.var1)
def __init__(self):
print (vars.var2)
print (vars.var3)
But yes, thank you very much for reading.
Unlike many other languages, class body is an executable statement in Python and is executed immediately as the interpreter reaches the class line. When you run this "program":
class Foo:
print("hey")
it just prints "hey" without any Foo object being created.
The same applies to the function definition statement def (but not to function bodies). When you run this:
def foo(arg=print("hi")):
print("not yet")
it prints "hi", but not "not yet".
When a class is created, Python executes all of the code directly inside the class declaration in a new namespace. This is so that any variables created in the class (most commonly methods, created by ordinary function declarations like def foo(self...)) are attached to the class rather than being global.
But the code still runs immediately. If it calls print() or does something else which creates a visible side effect, that will happen now, not when the class is instantiated (called to create a new instance). If you need something to happen when the class is instantiated, write an __init__() method instead.
main is a class not a function. Thus the code contained in the class declaration runs immediately because all statements are executed as they appear in code. As a method declaration is reached, it's bound to the class as a member, so in a way methods execute as well but are not called.
When Python read your code, it looked into class vars and defined all the variables. Then, it went into class main and executed the code there, as well as defining init. Python just executes whatever which is not in a function definition.

importing without executing the class - python

my problem is about i have a file that contain class and inside this class there is bunch of code will be executed
so whenever i import that file it will executed ! without creating an object of the class ! , here is the example
FILE X
class d:
def __init__(self):
print 'print this will NOT be printed'
print "this will be printed"
file B
import x
output is this will be printed, so my question is how to skip executing it until creating a new object?
You can't do that in Python, in Python every class is a first level object, a Python class is an object too and an class attribute can exist even if there is no instances of that class. If you just want to suppress the output of the print statement you can redirect the output of your print statements on the importing moment or create a context like the one provided in this first answer and use the __import__ statement manually.
If all you want to do is suppress the print (or any other executable statements) during import, surround them with a check for top module execution:
if __name__ == '__main__':
print 'this will be printed'
This will prevent the print during import, but allow it when the module is
executed interactively.
As others have pointed out, the second print statment is executing because it's one of the suite of statements making up the class declaration -- all of which are executed when the module they're in is imported because the declaration is part of its top-level code verses it being nested inside a function or method.
The first print statement isn't executed because it's part of a method definition, whose statements don't execute until it's called --- unlike those within a class definition. Typically a class's __init__() method is called indirectly when an instance of the class is created using the class's name, which would be d() for one named d like yours.
So, although it contradicts what's in the text of the strings being displayed, to make that second print statement only execute when instances of the class are created (just like with the first one) you'd need to also make it part of the same method (or called by it). In other words, after doing so, neither of them will execute when the file the class is in is imported, but both will when any instances of the class are created. Here's what I mean:
File x.py:
class d:
def __init__(self):
print 'print this will NOT be printed' # not true
print "this will be printed when object is created"
File b.py:
import x # no print statements execute
obj = d() # both print statements will be executed now
Your question is like: I have a function
def f():
print(1)
print(2)
How do I make print(1) executed, but not print(2)? There is really no easy way. What you have to understand is that def __init__(self) is also a statement. Your class consists of that statement and print statement. There is no easy way to execute one but not the other. Of course, if you can change the source of the class, just put the print inside __init__, where it will be called after instance creation.
(Copied from a comment above in case it is useful to future readers)
Agree with #mgilson and #EmmettJButler - this code is likely best-placed in the __init__. When Python imports a module, it executes the module-level code, including building the class definition with the class methods, etc. Therefore when you import X, and class d's definition gets built (so you can call it from B), it executes the code inside of the class. Usually this means you'll have class-level variables set and unbound methods ready to be attached to instances, but in your case it means that your statement will be printed.
As suggested by the others, refactoring the code is likely your best bet.

Python class that inherits from itself? How does this work?

Relatively new to Python, and I saw the following construct in the PyFacebook library (source here: http://github.com/sciyoshi/pyfacebook/blob/master/facebook/init.py#L660). I'm curious what this does because it appears to be a class that inherits from itself.
class AuthProxy(AuthProxy):
"""Special proxy for facebook.auth."""
def getSession(self):
"""Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=auth.getSession"""
...
return result
def createToken(self):
"""Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=auth.createToken"""
...
return token
what is this doing?
Tangentially related, I'm using PyDev in Eclipse and it's flagging this as an error. I'm guessing that's not the case. Anyway to let Eclipse know this is good?
The class statement there doesn't make the class inherit from itself, it creates a class object with the current value of AuthProxy as a superclass, and then assigns the class object to the variable 'AuthProxy', presumably overwriting the previously assigned AuthProxy that it inherited from.
Essentially, it's about the same as x = f(x): x isn't the value of f on itself, there's no circular dependence-- there's just the old x, and the new x. The old AuthProxy, and the new AuthProxy.
It's using the AuthProxy imported from a different module (check your imports) and deriving from it.
The "former" AuthProxy is created by __generate_proxies (it's not very nice code, there is even an exec and eval in it :)), but the author wanted also define some methods on top of it.
To make Eclipse stop whining about it, do this:
class AuthProxy(AuthProxy): ##UndefinedVariable

Categories