Bootstrap FreeKB - Python (Scripting) - Getting Starting with Classes
Python (Scripting) - Getting Starting with Classes

Updated:   |  Python (Scripting) articles

In Python, class is a reserved keyword that is used to define a class.

A class contains markup that can be used one or more times in a script. In this example, a class named "Hello" is defined that will simply print the text "World".

AVOID TROUBLE

The class must be define before the class is called in the script.

#!/usr/bin/python

class Hello:
  bar = "World"

foo = Hello()

print(Hello)
print(Hello())
print(foo)
print(foo.bar)

 

Which should return something like this.

<class '__main__.Hello'>
<__main__.Hello object at 0x7f7b6eb16940>
<__main__.Hello object at 0x7f7b6eb16940>
World

 

And here is one way to dump a class.

#!/usr/bin/python

class Hello:
  def __init__(self):
    self.name = 'John Doe'

vars = vars(Hello())

print(vars)

 

Which should return the following.

{'name': 'John Doe'}

 


Calling classes from another Python script

Often, shared classes are created in a "master" Python script, so that "child" Python scripts can use the shared classes.

Let's say classes.py contains the following.

#!/usr/bin/python
class Hello:
  bar = "World"

 

Here is how you could call classes.py from another Python script, such as testing.py. In this example, every class in classes.py will be made available in the testing.py script.

AVOID TROUBLE

The "master" Python script being imported will need to reside in one of the sys.path directories.

#!/usr/bin/python
from classes import *

foo = Hello()
print(foo.bar)

 

Or, if you want to limit the scope of the classes being imported, you can import specific functions.

#!/usr/bin/python
from classes import Hello

foo = Hello()
print(foo.bar)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 2beb14 in the box below so that we can be sure you are a human.