V
V
Vitaly2015-11-13 19:35:02
Python
Vitaly, 2015-11-13 19:35:02

What is the correct way to create a class in Python?

I create a class:

class settup():

    def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password
    def connect(self):
        try:
            self.a = Core(self.host)
        except:
            print '------ please check ip and try again -------'
            return False
        else:
            print '------ connected saccesseful -------'
            self.a.login(self.user, self.password)
            return True

Well, then I work with him.
s = settup(host, user, uspass)
if s.connect():
    print '==== what would you like to do ? ===='
    while True:
        do = raw_input('*** set up tunel press => 1 , check tunel press => 2  or press q to quit ***\n')
        if do == '1':
            local = raw_input('enter physical addres of this room => ')
            s.ip_sec(local)
            break
        elif do == '2':
            s.check_tunel()
            break
        elif do == 'q':
            print 'bay :)'
            break
sys.exit(0)

At first I wanted to do without the connect function in the settup class and put the code with try in __init__ but when I tried to return True or False from there I got an error that int can only return None
Now everything works, but is it correct?
Python 2.7

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2015-11-13
@deliro

0) PEP8 is crying for you
1) settup? What word is this?
2) self.a what is it?
3) what is uspass?
4) do == '1'? do is a verb and is used to refer to methods and functions, not variables.
5) print 'bay'? What is the connection between your code and bay?
6) In the connect method, the else block is optional. You can put return True at the end of try
7) Inherit the class from object
8) Create a field of the connected class and assign True or False to it and check in the connect method (if not self.connected). So you can get rid of multiple "connections"
9) except without a class is stupid to write, because even SyntaxError is skipped.
This is at first glance.

S
Stanislav Fateev, 2015-11-13
@svfat

Everything correctly __init__()cannot return values , if you want a value to be returned when creating an object of your class, use __new__():

class MyClass(object):
    def __init__(self):
        print u"не будет вызвано"
    def __new__(cls):
        return 42

obj = MyClass()
print obj

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question