Hey guys, I'm trying to learn how to use classes and work with seperate files, and I been reading about it and now I tryed making a little short "Hello World" thingy but I don't really understand the self. things, I thought I did but it's not working so I guess I diden't

Heres the code anyways:
HelloWorld.py

class HelloWorld :

        def __init__(self):

            print("Hi")

        def Talk(self ,name):

            self.nameA = name
            print("Hello",self.nameA)

Main.py

import HelloWorld

HelloWorld.HelloWorld.Talk("Kevin")

I get the error:

Traceback (most recent call last):
  File "D:\PygameSpel\Test med klasser\Main.py", line 3, in <module>
    HelloWorld.HelloWorld.Talk("Kevin")
TypeError: Talk() takes exactly 2 arguments (1 given)

what am I missing?

Recommended Answers

All 6 Replies

You have not created instance of HelloWorld object, but try to access the class method without reference to instance (self parameter).

class HelloWorld:
        def __init__(self ,name='friend'):
            self.name = name
        def __str__(self):
            return "Hello, %s!" % self.name


print HelloWorld()
print HelloWorld('pyTony')

A class is a prototype, i.e. it is only a potential object.

class HelloWorld :

        def __init__(self):

            print("Hi")

        def talk(self ,name):

            self.nameA = name
            print("Hello", self.nameA)

HW1=HelloWorld()     ## calls the class or creates an actual instance
HW2=HelloWorld()     ## a second, separate instance

HW1.talk("Name 1")
HW2.talk("Name Two")

print HW1.nameA
print HW2.nameA

Yeah well, that works perfectly if I only run the HelloWorld.py file, but the thing is I want to send a name from the main.py to the HelloWorld.py file and thats the thing I don't get how to do properly

OK, perhaps we need to start over from scratch. What you need to understand is that an object is a model of something. It can be something real, like a car or a person, or something conceptual, like a list or a dictionary (I use those examples because, as it happens, lists and dictionaries are objects in Python). The point is that the object captures or encapsulates the properties of the thing it is modeling, its current state, and its potential behavior. The properties and state are described by variables that are part of the object, called instance variables, and the behavior is described by functions which are bound to the object, called instance methods.

A class is a description of an object, a sort of template or mold for making new objects. It defines both the instance variables of the object, and the methods the object can perform. It works by providing a way of creating a new object - the __init__() method, also known as the constructor or c'tor. The c'tor primary job is to set the initial values of the object's instance variables. It can do anything that you can do in any other method, but it should initialize the instance variables in some way.

In Python the first argument of any instance method is the object itself, which by convention is named self. This is true of the __init__() method as well, even though it is actually not an instance method per se (it is a special case of something known as a class method, which I'll get to later). All access to the instance variables goes through the self variable, using the dot-notation which should already be familiar to you from using lists and dictionaries. The self variable is implicit in the call to the method, so you don't need to pass it to the c'tor directly.

So, let's say you have a class called Greeting, which represents a simple message to someone. You could define the class and c'tor, and a method we'll call send() as so:

class Greeting (object):
    def __init__(self, msg, recpt):
        self.message = msg       # add an instance variable called 'message'
        self.recipient = recpt   # add another instance variable called 'recipient'
        self.sent = False        # add an instance variable called 'sent'

    def send(self):
        if not self.sent:
            print "Dear {name}: {msg}".format(name=self.recipient, msg=self.message)
            self.sent = True

Now, if you want to use this in a separate file, you would do something liek so:

from greeting import Greeting

hello = Greeting("Hello!", "Jay Osako")
hello.send()
commented: Thanks man! This was exactly what I was looking for +0

Here is an example that you can play with ...

'''Class_Animal1.py
a look at a simple Python class

a class combines methods/functions that belong together
to keep methods private, prefix with a double underline only

see also:
http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
tested with python27, python32, python33
'''

class Animal():
    """
    class names by convention are capitalized
    """
    def __init__(self, animal, sound):
        """
        __init__() is the 'constructor' of the class instance
        when you create an instance of Animal you have to supply
        it with the name and the sound of the animal
        'self' refers to the instance
        if the instance is dog, then
        name and sound will be that of the dog
        'self' also makes name and sound available
        to all the methods within the class
        """
        self.name = animal
        self.sound = sound

    def speak(self):
        """
        the first argument of a class method is always self
        this method needs to be called with self.speak() within
        the class, or the instance_name.speak() outside the class
        """
        print("The %s goes %s" % (self.name, self.sound))


# create a few class instances
# remember to supply the name and the sound for each animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = Animal("cow", "mooh")

# now you can call each animal's function/method speak()
# by simply connecting instance_name and speak() with a '.'
cow.speak()
cat.speak()
dog.speak()

# you can also access variables associated with the instance
# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound)

Thanks for the help everyone, Schol-R-LEA you are truly awesome! Every problem I have had and posted on here you have shown me how to do it. Great thanks to you man!

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.