class implementation

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Oct 6 21:24:45 EDT 2013


On Sun, 06 Oct 2013 06:15:51 -0700, markotaht wrote:

> There is this class file, it has its functions and variables. 

What's a class file?

Do you mean a file containing only a single class? 


> Now im
> greating my program, that uses the funcions from the class.

They are called "methods".


> BUt there
> are some functions missing from the class. So i want to add some extra
> funtions to the class, whidout altering the original source code, but by
> extending it in my code. But for that i need to use some variables that
> exsist in the original class. Is there a way i can acccsess them?

When you say "variables", we prefer to say "attributes".

A string variable is a variable that holds a string.
An int variable is a variable that holds an int.
A list variable is a variable that holds a list.
A float variable is a variable that holds a float.

So... 

...a class variable is a variable that holds a class, and an instance 
variable is a variable that holds an instance.


When extending classes, you access attributes exactly the same way you 
would access them if you were writing the class in the first place.

class Test(object):
    def __init__(self, arg):
        self.arg = arg  # Store the arg as an instance attribute.
    def method(self):
        print("arg is", self.arg)


class NewTest(Test):  # subclass to add new methods
    def add_one(self):
        return self.arg+1


For experts only: sometimes you need to extend the class itself. You can 
do that by adding methods to the class:

def minus_one(self):
    return self.arg-1

NewTest.minus_one = minus_one



-- 
Steven



More information about the Python-list mailing list