My next step in python: Classes

Greetings, during my journey to enlightenment, I’ve reached a satisfatory level of self sustainability. Thias means I’m confident enough to solve my own problems using my own code. I still have a long way to go, as efficient an clean code goes, but still, that’s a great step to me, and I have to thank the community for that. Special thanks as well to : Monster, SolarLune, Écrivain, Agoose77, Jplur, Goran, and others.

My next step is then the use of more advanced features like custom classes.
Since I’ve never used one, I don’t really know much about them. How far do they reach (what can be done with them)?
Well, these are rather rethorical questions, the real ones are: Is there a specific format, or rules to bid to?
How do I use my class in my other scripts?
Is there something unique that can only be done using classes.

Rmember, I’m posting these questions here in a pratical way of learning, instead of the standard procedure.

Thank you fro all your help!

Nice to see your taking the Initiative to learn! at the moment you may he aware that I have a python tutorial ongoing on my tutorial website. I believe I have covered classes in episode 2!
http://hostilestudios.com/bge/

You might want to read about object orientated programming first. Classes are “just” parts of it.

Hints:
When reading tutorials try to answer this questions:

  • What is the difference between a class and an instance (object)?
  • What is inheritances?

I hope it helps you ;).
Monster

@torakunsama
hey.. this is great! I am learning about classes now too! :slight_smile:
My brother has teached me a bit already.

Classes are usefull for example if you want to create a variety of objects.. Lets say different enemy types.
You can write a basis class with basic functions for an enemy.
Now you can create a second enemyclass which is a variation of the basis class. You can inherit alle important basisfunctions, but you can expand them, change them.. whatever you like :slight_smile:

What is great, that you have an init function. with it you can create all important variables once, because the init function gets executed only one time when you create the object! So the variables will not get overwritten each tic.
You don’t need to write code redundant for different enemy types. You can reuse a lot of code.

I have attached a file I have prepared that shows how to use a class. I hope it helps you. I am also a beginner in this section. So maybe we can learn together :smiley:

Attachments

Classes.blend (400 KB)

I’m very pleased by all the replies!
@ agoose77: I could just go and follow tutorials. Unfortunately, I spend 10 hours at work where most sites are filtered (somehow BA.org as well, but not the subforums O.o?), so I have no access to sites like those, unless I’m at home. I get home by 7MP, after a hard day of accounting(what I do for a living…) and my head is at it’s limits, so learning at that time is couter productive. But I’ll read it anyways, thank you!

@ Monster: Same reason as above, that’s why I rely so much on the community! Well, I’ll follow your advice. Thank you!

@ndee: Thank you very much for the info an tips. Yourexample will certainly be of great help!
as fellow beginner I hope this thread will help us both and anyone reading (in need of learning).

OOP for the win. This alone is the way to code aha.
I joke of course, but I love the fact you are seeking knowledge on your own and not because you have come against a wall, well done indeen torakunsama. :slight_smile:

I just checked the byteOfPython manual. It contains a small section covering some important things on OOP. It is easier to understand than for example the wikipedia. So I suggest to check it.

My file is named byteofpython_120.pdf. I think I saw it in German too. Maybe it is available in your mother tongue.

… here it is: http://www.swaroopch.com/notes/Python

and the direct link to oop

Classes, sdfgeoff style:

By now you have probably learned about functions, and how you can use them to hold operations. Well, a class is a way to store functions.

In a script there is often more than one thing happening, so you might read a file, then get a bit of information from it, interpret that information, and finally act on it.
Classes allow you to divide up your script into the different sections.
So you can have a class for your file management functions, and a class for your AI functions, and so-on/so-forth until you get tired.

To use a class you have to create it (obviously), and to do so you use the class statement. For example this will create a class called AI:


class AI:

And then you put your functions in it, like so:


class AI:
    def getAngleBetween(source, target, axis):
        '''Get's the angle between source and target'''
        dis, gvec, lvec = source.getVectTo(target)
        angle = lvec.angle(mathutils.Vector(axis),90)
        angleDeg = math.degrees(angle)
        return angleDeg
    

    def hasDirectSightOn(source, target):
        '''See's if there's a direct line between the source and target'''
        hitObject = source.rayCastTo(target)
        return id(hitObject) == id(target)
    
    def seeking(obj, cont, LR, UD):
        '''Activates the actuator 'seek' and deactivates the tracking'''
        seek = cont.actuators["seek"]
        cont.activate(seek)
        cont.deactivate(LR)
        cont.deactivate(UD)

And so on.

So then you want to use one of these functions, so you have to call it.
You do it in the same way as you do a module, so to call getAngleBetween you use:


AI.getAngleBetween(obj, enemy, [0,0,1])

From anywhere in the script.

Say that for part of the function “getAngleBetween” we called the function “seeking” We can refer to it by using AI.seeking, like you would from out of the class, but the preferred way is to use a thing called “self.”
When you write your function, have as the first parameter “self” You do not need to put anything in that when you call it.

So getAngleBetween becomes:


    def getAngleBetween(self, source, target, axis):
        '''Get's the angle between source and target'''
        dis, gvec, lvec = source.getVectTo(target)
        angle = lvec.angle(mathutils.Vector(axis),90)
        angleDeg = math.degrees(angle)
        return angleDeg

Then to refer to another function in the same class you use:

 self.seeking

This is the limit of my knowledge of classes at the moment, I only learned about them about 2 months ago, so I’m probably missing heaps.

Good Luck
sdfgeoff out

A small miss in Your code - Methods should have self as there first argument - but it is not used when calling the function. But it is used for from a method accessing fields (object variables) and calling other methods (functions) on the same object.

A class is a way to store functionality and state that belong together in one unit - a custom type. Put in other words. Grouping functions and variables handling the same thing.

And if You have more then one of those things You can create more than one object of the same class to handle them.

Thank you very much everyone!

@ Monster: That page really helped a lot!

@ sdfgeoff: Hmm, I see, That’s what I was missing. As with time I reealized that functions are like code islands that do their own thing… classes are more like continnents having different countries working together (countries = functions). Thnak you for the explanation.

@ Lah: Indeed, I believe is time for me to clean up my code and start using classes! Thank you for clarifying the .self part.

I believe my knowledge has just extended more now. If I had asked about classes earlier, when functions were still the greatest thing I had found, I’d probably get a bit confused (maybe not, and would have saved a lot of time…), so I think the timing was right.

For all participants thank you very much, once again, for all your prompt assistance!

Thanks Lah for improving my understanding of this!
I’ll update the text

@ Monster: indeed! I was planning on doing that. I’ll use classes for what they do best, custom objects. Simpler and less calculi intense is better!

Now, I don’t know what my next step will be, I guess I have to move forward to know!

A little note about classes. You cannot call the self keyword until you initialize it with an Init function. Also, you cannot access instance variables without installing a class.

self is no keyword. It is the first argument in your formal parameter list.
By convention it should be called ‘self’. See byteOfPython
You do not need to define an empty init() as it is inherited by the base class “object” see Python docs.

@agoose77: What do you mean with installing a class?I do not get what you mean ::confused: