TIME NOW
World current time now,
CALENDAR
Calendar monthly, yearly
login CONVERT LENGTH
login CONVERT TEMPERATURE
login DICTIONARIES, LISTS
login SCIENCE EDUCATION RELIGION
login WORK CALCULATOR
login CALCULATE LIFE

Python 3 programming language, learn python, tutorial

Previous articlePage bottomNext article  ALL TOPICS

Python 3. Classes and Objects

 1. Class:
class MyClass:
    """A simple example class"""

    i = 12345

    def f(self):
        # self is object current object
        return 'hello world'

# Declaration
x = MyClass()

# variable
print (x.i)

# method
print (x.f())

Self:
http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self-in-python

2.
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Complex(3.0, -4.5)
print( x.r, x.i )

3. Methods and attributes
class Dog:

    kind = 'canine'         

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

d = Dog('Fido')
e = Dog('Buddy')
print ( d.kind , e.kind )                  
print ( d.name , e.name )                  

4. Common for all objects list tricks
class Dog:

    tricks = []             # mistaken use of a class variable

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

    def add_trick(self, trick):
        self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')

d.add_trick('roll over')
e.add_trick('play dead')

# full common list for both (logical error)
print(d.tricks, e.tricks)

4.a.
class Dog:

    tricks = [1]             # mistaken use of a class variable

    def __init__(self, name):
        self.name = name
        print (self.tricks)
        self.tricks.append("data")
        self.tricks.insert(0, "insertData")

    def add_trick(self, trick):
        self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')

d.add_trick('roll over')
e.add_trick('play dead')

# common error again
print(d.tricks, e.tricks)

5.
class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')

print (d.tricks, e.tricks)

6. Methods may call other methods by using method attributes of the self argument:
class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)

bag = Bag()
bag.addtwice("data")
print(bag.data)

6a. Old style and new style classes. 
class MyClass(object): = new-style class
class MyClass: = new-style class (implicitly inherits from object)

New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super(), @property and descriptors. In the absence of any other superclasses that you specifically want to inherit from, the superclass should always be object, which is the root of all classes in Python. object is technically the root of "new-style" classes in Python. But the new-style classes today are as good as being the only style of classes.
https://stackoverflow.com/questions/54867/what-is-the-difference-between-old-style-and-new-style-classes-in-python:
# New style
class NewStyle(object):
    pass
 
class AnotherExampleOfNewStyle(NewStyle):
    pass
 
# Old style
class OldStyle():
    pass
 
class OldStyleSubclass(OldStyle):
    pass

7. Classes and modules. __str__ - string representation of object ).
module.py file. Call module.py file directly:
class Pet(object):

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

    def getName(self):
        return self.name

    def getSpecies(self):
        return self.species

    def __str__(self):
        return "%s is a %s" % (self.name, self.species)
 
print ( __name__)
 
# One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. 
if __name__=='__main__':
    a = Pet("jax", "human")
    print (a)

hello.py. First print is executed. condition is false. Call module.py indirectly:
import module

hello1.py. First print is executed. condition is false:
from module import Pet

# object
polly = Pet("Polly", "Parrot")

# property of the object
print ("Polly is a %s" % polly.getSpecies())

# calling the class. set object name self = "polly"
print ("Polly is a %s" % Pet.getSpecies(polly))

# calling the class. no object name - error
print ("Polly is a %s" % Pet.getSpecies())

hello2.py. First print is executed. condition is false:
from module import Pet

polly = Pet("Polly", "Parrot")

print (polly.getName())

print (polly.getSpecies())

# print textual representation of the object
print (polly)

8.
module.py:
class Pet(object):

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

    def getName(self):
        return self.name

    def getSpecies(self):
        return self.species

    def __str__(self):
        return "%s is a %s" % (self.name, self.species)

class Dog(Pet):

    def __init__(self, name, chases_cats):

        # COMMENT , UNCOMMENT !!!
        Pet.__init__(self, name, "Dog")
        self.chases_cats = chases_cats

    def chasesCats(self):
        return self.chases_cats

class Cat(Pet):

    def __init__(self, name, hates_dogs):
        Pet.__init__(self, name, "Cat")
        self.hates_dogs = hates_dogs

    def hatesDogs(self):
        return self.hates_dogs

hello.py:
from module import Pet, Dog

# parent object
mister_pet = Pet("Mister", "Dog")

# child object
mister_dog = Dog("Mister", True)

###

print("01 ", isinstance(mister_pet, Pet))

print("02 ", isinstance(mister_pet, Dog))

print("03 ", isinstance(mister_dog, Pet))

print("04 ", isinstance(mister_dog, Dog))

###

print("11 ", mister_dog.chasesCats())

print("12 ", mister_pet.getName())

print("13 ", mister_dog.getName())

# error
print("14 ", mister_pet.chasesCats())

 

9.
module.py is the same.

hello.py:
from module import Cat, Dog

fido = Dog("Fido", True)
rover = Dog("Rover", False)
mittens = Cat("Mittens", True)
fluffy = Cat("Fluffy", False)

###

print (fido)

print (rover)

print (mittens)

print (fluffy)

print ("%s chases cats: %s" % (fido.getName(), fido.chasesCats()))

print ("%s chases cats: %s" % (rover.getName(), rover.chasesCats()))

print ("%s hates dogs: %s" % (mittens.getName(), mittens.hatesDogs()))

print ("%s hates dogs: %s" % (fluffy.getName(), fluffy.hatesDogs()))

10.
class Employee:
    pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

11. Global variables:
count = 0

class store:
    def add(self):
        
                # exists
        global count
                
                # not exists
        global set;
                
        count += 1
        try:
            set += 1
        except:
            set = 1
        
a = store()

a.add()
a.add()
a.add()

print (count, " " , set)

Task:
1. Class= NAMAS; 2 savybes,  2 metodai
|
Subclass = 2. DAUGIABUTIS, 3. NUOSAVAS , 2 savybes,  2 metodai
|
Sub sub class = 4. KULTŪROS PAVELDO KLASÄ–, 5. PAPRASTAS, 2 savybes,  2 metodai

Iškviesti savybes ir metodus
 

12. https://docs.python.org/3/tutorial/classes.html#private-variables
# Private variables __variable
# It's not about forbidding access or hiding something, it's about implicit # API documentation.
#Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores.
# Python is very good tool. But it is simplified OOP language.

class A:
    def __init__(self):
        self.__var = 123
    def printVar(self):
        print (self.__var)


x = A()
#print(x.__var)

x.printVar()

print(x._A__var)
x._A__var = 456 # you now know the masked name of private variables
x.printVar() # this gives back 456


print (x.__dict__)

12 Abstract Base Classes
kaip i6skirti kintamajam kiek norim vietos.
private
@property decoratot
-- 
Previous articlePage topNext article  ALL TOPICS


Guest:
class duomenys:

def ived(self):
print("\n","-"*15,"Ivedimas","-"*15,"\n")
while True:
fname='Vardas'
while fname!='':
fname = input("Vardas: ")
fname=fname.replace("1","")
fname=fname.replace("2","")
fname=fname.replace("3","")
fname=fname.replace("4","")
fname=fname.replace("5","")
fname=fname.replace("6","")
fname=fname.replace("7","")
fname=fname.replace("8","")
fname=fname.replace("9","")
fname=fname.replace("0","")
if fname=='':
print("Vardas turi buti sudaritas tik is raidziu. Bandikite dar karta.")
else:
break
if fname!='':
break
while True:
lname='Pavarde'
while lname!='':
lname = input("Pavarde: ")
lname=lname.replace("1","")
lname=lname.replace("2","")
lname=lname.replace("3","")
lname=lname.replace("4","")
lname=lname.replace("5","")
lname=lname.replace("6","")
lname=lname.replace("7","")
lname=lname.replace("8","")
lname=lname.replace("9","")
lname=lname.replace("0","")
if lname=='':
print("Pavarde turi buti sudaritas tik is raidziu. Bandikite dar karta.")
else:
break
if lname!='':
break
f = open('file.txt','a')
f.write("\""+fname+"\";\""+lname+"\";\n")
print("\nPapildyta!")
def spaus(self):
print("\n","-"*15,"Failo turinys","-"*15,"\n")
f = open('file.txt','r')
print(str("Vardas").ljust(15),"Pavarde\n","-"*30)
n=1
while True:
string = f.readline()
if string!="":
list=string.split(';',1)
list[0]=list[0].replace("\"","")
list[0]=list[0].replace(";","")
list[1]=list[1].replace("\"","")
list[1]=list[1].replace(";","")
list[1]=list[1].replace("\n","")
print(n,"-",str(list[0]).ljust(15),list[1])
n+=1
else:
break
def trin(self):
f = open('file.txt','w')
print("\n","-"*15,"Sarasas tuscias","-"*15,"\n")

def eiltrin(self):
list=[]
f = open('file.txt','r')
while True:
string = f.readline()
if string!="":
list.append(string)
else:
break
y=0
while True:
try:
while y<1 or y>len(list):
y=int(input("Kuria eilute istrinti?  "))
except ValueError:
print("Eilutes Nr")
else:
break
f = open('file.txt','w')
for l in range(0,len(list)):
if l!=y-1:
f.write(list[l])

def spausHTML(self):
print("\n","-"*15,"HTML","-"*15,"\n")
HTML=""
f = open('file.txt','r')
print(str("Vardas").ljust(15),"Pavarde\n","-"*30)
n=1
while True:
string = f.readline()
if string!="":
list=string.split(';',1)
list[0]=list[0].replace("\"","")
list[0]=list[0].replace(";","")
list[1]=list[1].replace("\"","")
list[1]=list[1].replace(";","")
list[1]=list[1].replace("\n","")
HTML+="<tr><td>" + str(n) + "</td><td>" + list[0] + "</td><td>"+ list[1] + "</td></tr>\n"
n+=1
else:
break
  
HTMLfin="<html><head></head><body><h1>DUOMENYS</h1><table border = 1 >\n" + HTML + "\n</table></body></html>"
  
f.close()
#print (HTMLfin)
  
fHTML = open('c:/xampp/htdocs/index.html','w')
fHTML.write(HTMLfin)
fHTML.close()
def menu(self, x):
while x<1 or x>6:
print("\n","-"*10,"Pasirinkimu menu","-"*10,"\n")
x=int(input("1 - Papildyti\n2 - Isvesti\n3 - Istrinti viska\n4 - Istrinti eilute\n5 - Spausdinti\n6 - Baigti\n"))
return x


----

from module import duomenys
x=0
list=[]

d = duomenys()

while True:
if x==1:
d.ived()
if x==2:
d.spaus()
if x==3:
d.trin()
if x==4:
d.eiltrin()
if x==5:
d.spausHTML()
x=0
x=d.menu(x)
if x==6:
break


2015-12-08 09:06:22
Tomas:
Gzip
gzip is a file format and a software application used for file compression and decompression.
(Writing Compressed Files)
import gzip
import os

outfilename = 'example.txt.gz'
output = gzip.open(outfilename, 'wb')
try:
    output.write('Contents of the example file go here.\n')
finally:
    output.close()

print outfilename, 'contains', os.stat(outfilename).st_size, 'bytes of compressed data'
os.system('file -b --mime %s' % outfilename)

(Reading Compressed Data)
import gzip

input_file = gzip.open('example.txt.gz', 'rb')
try:
    print input_file.read()
finally:
    input_file.close()



2016-04-26 01:43:36
Tomas:
Poplib
 
This module defines a class, POP3, which encapsulates a connection to a POP3 server and implements the protocol
 
import getpass, poplib
 
M = poplib.POP3('jakas.serveriai.lt')
M.pass_('bfMEN75f')
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print(j)
 


2016-04-26 01:44:18
Tomas:
import smtplib
from email.mime.text import MIMEText

title = 'My title'
msg_content = 'aaaa'
message = MIMEText(msg_content, 'html')

message['From'] = 'Sender Name <[email protected]>'
message['To'] = 'Receiver Name <[email protected]>'
message['Subject'] = 'Any subject'

msg_full = message.as_string()

server = smtplib.SMTP('jakas.serveriai.lt',25,timeout=30)
server.set_debuglevel(1)
server.starttls()
server.login([email protected]', 'aaaa')
server.sendmail([email protected]',
                ['[email protected]', '[email protected]'],
                msg_full)
server.quit()



2016-04-26 01:45:45

 Use username: Guest, Anonymous, Programmer






QUOTES:
Being with him just made me feel better. I always pictured him as a big, happy person.
Chris Salabye
A mere friend will agree with you, but a real friend will argue.
Assyrian Proverb
The person who has the will to undergo all labor may win any goal.
Menander of Athens