Hey guys, I was wondering if you could clear up some things on classes for me. I have had a semi-easy time understanding python and programming concepts up to this point but now am having a real tough time on classes. I think it is because my book uses long and confusing examples to show how they work. Anyways, I made a short, 8 line class to try and understand what is going on.

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        self.name = playername

    def getName(self):
        return self.name

My first question is, the self.name under the constructor, I do not really unerstand what to put under here (the constructor). For this example it is easy because I only have one method but what else would be put under there and how would they work with the methods? Second, when I create an object of this class ( I hope I am using the right vocab :P ) "josh", I can use josh.name to get the same result as josh.getName(). So what is the purpose of the getName() method?

If anyone wants to answer this that would be great, or another thing that could be great is if someone made a slightly more complex class and explained how everything worked together. Thanks in advance!

Second, when I create an object of this class ( I hope I am using the right vocab ) "josh", I can use josh.name to get the same result as josh.getName(). So what is the purpose of the getName() method

Not a Pythin guy but in other OOp languages like C++ and Java, there is a term called Encapsulation. That means that fields can have a visibility modifier e.g. public or private. Private fields cannot be accessed from outside the class whereas public ones can. To change these you therefore need mutator and accessor (get* and set*) methods.


Proably easier if i explain it - E.g

You may have a class called person with a field called age. It is a good idea to make age private because you DONT want to allow people to access it directly. Instead, use a mutator method, which takes a value as a paramater,. e.g. james.setAge(19) . This way you can perform validation e.g checking i dont input an age of less than zero or something.

tha getName in your code is an example of an Accessor metho - it just returns the value of name.

Member Avatar for masterofpuppets

hi,
here's an example class to represent students :)

import datetime

class Student:
    def __init__( self, firstname, lastname, birthdate, matricNum, gender ):
        self.firstname = firstname
        self.lastname = lastname
        self.birthdate = birthdate
        self.matriculationNum = matricNum
        self.gender = gender

    def getFirstName( self ):
        return self.firstname
    def getLastName( self ):
        return self.lastname
    def getBirthdate( self ):
        return self.birthdate
    def getMatricNum( self ):
        return self.matriculationNum
    def getGender( self ):
        return gender

    def displayStudent( self ):
        return self.matriculationNum + " " + self.lastname + " " + self.firstname

    def getDate( self ):
        return datetime.datetime.today().strftime( "%d" ), datetime.datetime.today().strftime( "%m" ), datetime.datetime.today().strftime( "%Y" )

    def age( self ):
        day, month, year = self.getDate()
        stDay, stMon, stYear = self.birthdate.split( "/" )[ 0 ], self.birthdate.split( "/" )[ 1 ], self.birthdate.split( "/" )[ 2 ]
        ageInYears = int( year ) - int( stYear )

        if int( month ) < int( stMon ) or ( int( month ) == int( stMon ) and int( day ) < int( stDay ) ):
            ageInYears -= 1
        return ageInYears

    def emailAddress( self ):
        return self.matriculationNum + "@university.uk"

    
student1 = Student( "John", "Smith", "07/10/1989", "123456", "male" )
student2 = Student( "Matthew", "Jones", "13/11/1986", "987654", "male" )

print student1.displayStudent()
print student1.getBirthdate()
print student1.age()
print student1.emailAddress()
print
print student2.displayStudent()
print student2.getBirthdate()
print student2.age()
print student2.emailAddress()

it's just to illustrate some of the main points...
The __init__ method is the constructor for the class, so here you can put all the relevant variables that you're going to use in the whole class and you can access these variable by using 'self', by providing it as a parameter in every method.
As for your second question - about the getName( self ) method. Some variables can be declared as 'private' to the class, meaning that you cannot access them from anywhere else except in the class, that's why you need a 'getter' for the private variable. However I am not sure whether Python supports private variables :) but in Java you definitely need a method like getName() or wtevr.
Hope this makes it a bit clearer....I haven't actually worked a lot with classes in Python but I guess it is not that much different to Java. So I am sorry if I didn't explain something properly... still learning as well :)

This is my first time actually providing an answer on these forums so here goes..
A class is something like a template.
There are a few special method associated with classes and the __init__ method is one of those. (more on that later).

Imagine a class representing a person.
This person would have several "attributes" like name, age, gender etc.

In such a situation, an object created by a class (with the necessary code in the __init__ method) would have the attributes name age and gender.

So, in the init method, you would include the following.

class Person:
    def __init__(self,name,age ,gender):
        self.name = name.
        self.age = age
        self.gender = gender

when you make a person by typing
Josh = Person('josh',10,male)
the arguments you provided will be used by the __init__ method to create attributes of josh.
so, Josh.name = josh.
Josh.age = 10
and josh.gender = male.

I hope I did a good job explaining this.
I would highly recomment "a byte of python" by swaroop CH. A free PDF manual for python. Explains classes beautifully.

It`s not the best example of python class masterofpuppets.
You put in lot effort to help wish is fine.

Hope this makes it a bit clearer....I haven't actually worked a lot with classes in Python but I guess it is not that much different to Java. So I am sorry if I didn't explain something properly... still learning as well

Python is not java,it`s a lot better:cool:
http://dirtsimple.org/2004/12/python-is-not-java.html
Just to point it out that you could have dropped all that getters method.

Form article.

don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.

Look at this and then think of how you code could have been shorter and better.
http://tomayko.com/writings/getters-setters-fuxors

commented: Great articles. I like the authors' points of view on Python. Inspiring! +3

don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well.

By using encapsulation you ensure fidelity of data, and provide a known interface to others who may extend or use your class, making refactoring much less painful.

By using encapsulation you ensure fidelity of data, and provide a known interface to others who may extend or use your class, making refactoring much less painful.

The author of the article meant that the "property" function replaces getters and setters. In fact python's "property" encapsulates the attribute, and also encapsulates getters and setters !

Just expanding on my previous post...
try making this
josh = Person()

then type josh.name and josh.age.
You get noting... You have to pass the arguments when making the object. The __init__ method actually "assigns" (to the experts: Is my terminology correct?) them to the object.

Back to the original code, this would have made more sense ...

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        self.name = playername

    def getName(self):
        return "I am %s" % self.name

# create the class instance bob
bob = Player("Bob")

print(bob.name)      # Bob
print(bob.getName()) # I am Bob

... or making the name private to the class ...

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        # double underline prefix makes 
        # __name private to the class
        self.__name = playername

    def getName(self):
        return self.__name

# create the class instance bob
bob = Player("Bob")
try:
    # you cannot access a private class variable
    # so it would be an error, nothing will print
    print(bob.__name)
except:
    pass
# now you have to use the method to get the name
print(bob.getName())  # Bob
Member Avatar for masterofpuppets

Back to the original code, this would have made more sense ...

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        self.name = playername

    def getName(self):
        return "I am %s" % self.name

# create the class instance bob
bob = Player("Bob")

print(bob.name)      # Bob
print(bob.getName()) # I am Bob

... or making the name private to the class ...

class Player:
    """Enter name as string"""

    def __init__(self, playername):
        # double underline prefix makes 
        # __name private to the class
        self.__name = playername

    def getName(self):
        return self.__name

# create the class instance bob
bob = Player("Bob")
try:
    # you cannot access a private class variable
    # so it would be an error, nothing will print
    print(bob.__name)
except:
    pass
# now you have to use the method to get the name
print(bob.getName())  # Bob

wow thanks for that dude I was actually wondering how to create private variables in Python. That really helped :)

wow thanks for that dude I was actually wondering how to create private variables in Python. That really helped :)

Yes, but be forewarned it's psuedo-private. You can still see and access the variable, it's just obfuscated with the Class name. Look:

>>> class Cpriv(object):
...     def __init__(self):
...         self.__privy = 'I am hidden'
...     
>>> C = Cpriv()
>>> dir(C)
['_Cpriv__privy', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> print C._Cpriv__privy
I am hidden
>>>

The reason you want to make something private to the class is to keep it from easily spilling out into external code. So pseudo-private will do one good job. Remember it's called private, not secret!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.