class Person:
def __init__(self, nameInput, addressInput, dateOfBirthInput):
self._name = nameInput
self._address = addressInput
self._dateOfBirth = dateOfBirthInput
def getName(self):
return self._name
def getAddress(self):
return self._address
def getDateOfBirth(self):
return self._dateOfBirth
def __repr__(self):
return 'Name: %s \nAddress: %s \nDate of Birth: %s' % (self._name, self._address, self._dateOfBirth)
The first class will output properly if I put in something like kat = Person('CC','9th Street','1990'). But I can't get it to work correctly when I try to call it from within a subclass, it just leaves everything blank.
from Person import Person
class Employee(Person):
def __init__(self, nameInput, addressInput, dateOfBirthInput, employeeNumberInput, dateOfHireInput):
super().__init__(nameInput, addressInput, dateOfBirthInput)
self._employeeNumber = employeeNumberInput
self._dateOfHire = dateOfHireInput
def getEmployeeNumber(self):
return self._employeeNumber
def getDateOfHire(self):
return self._dateOfHire
def __repr__(self):
return super().__repr__() + '\nEmployee Number: %s \nDate Of Hire: %s' % (self._employeeNumber, self._dateOfHire)
If I were to input something like kat = Employee('CC','9th Street','1990','12345','2017') into the block above I get nothing, am I missing something obvious, I've rewritten it a few different ways to match examples but neither my ways nor the examples work for me.
So after some fiddling it seems there isn't anything wrong at all, whether it runs or not seems to be decided by what I run it with. I wrote it in Visual Studio and it didn't work in that, but it works fine when I shove it in Idle.
Do this in your Employee class
class Employee(Person):
...: def __init__(self, nameInput, addressInput, dateOfBirthInput, employeeNumberInput, dateOfHireInput):
...: super(Employee, self).__init__(nameInput, addressInput, dateOfBirthInput)
...: self._employeeNumber = employeeNumberInput
...: self._dateOfHire = dateOfHireInput
...: def getEmployeeNumber(self):
...: return self._employeeNumber
...: def getDateOfHire(self):
...: return self._dateOfHire
...: def __repr__(self):
...: return super(Employee, self).__repr__() + '\nEmployee Number: %s \nDate Of Hire: %s' % (self._employeeNumber, self._dateOfHire)
this will work for your module
Related
I have a number of classes where there are functions inside are almost the same.
Say function x:
class A():
def x_A (self):
...
...do the same thing
...
run a function that is unique in class A itself, say u_A
...
...do the same thing
...
class B():
def x_B (self):
...
...do the same thing
..
run a function that is unique in class B itself, say u_B
...
...do the same thing
...
So I came up with an idea to re-write function x in a new class(say x_C in class C) to replace x_A and x_B. And I just have to import that new class when I need it. something like:
import C
class A():
def x_A (self):
C.x_C(u_A)
class B():
def x_B (self):
C.x_C(u_A)
but I am confused of how to pass in the unique function (u_A and u_B) as a variable and make python to run it properly.
class C():
def x_C (self,unique_function):
...
...do the same thing
..
run unique_function here
...
...do the same thing
...
Thx in advance
blow is newly edited:
hi trying to specify my question:
I have a number of crawlers, at the end of each I got "run_before_insert" to check if they can run properly.
Currently I just copy and paste this function at end of every finished crawler with some edits.
But now I would like to simplify my code by importing "run_before_insert" from other files, and then comes my questions.
def run_before_insert(self):
try:
#store_list = []
comp_name = 'HangTen'
start = time.time()
print('{} runBeforeInsert START'.format(comp_name), '\n')
###Here is the part where small edits in the function:
store_list = self.get_stores_2()
###the rest is the same
script_info = {}
running_time = round(time.time() - start,2)
total = str(len(store_list))
script_info['running_time'] = running_time
script_info['total_stores'] = total
print('\n{} total stores : {}'.format(comp_name,script_info['total_stores']), '\n')
print('{} running time : {}'.format(comp_name,script_info['running_time']), '\n')
print('{} runBeforeInsert Done'.format(comp_name), '\n')
print('\n')
return script_info
except Exception as e:
traceback.print_exc()
script_info = {}
script_info['running_time'] = '--'
script_info['total_stores'] = 'error'
return script_info
print(e)
Here is my code with reference to #juanpa.arrivillaga:
class run_pkg_class():
def __init__(self):
pass
def run_before_insert(self, store_function, company_name):
try:
comp_name = company_name
start = time.time()
print('{} runBeforeInsert START'.format(comp_name), '\n')
###
store_list = store_function()
###
script_info = {}
running_time = round(time.time() - start,2)
total = str(len(store_list))
script_info['running_time'] = running_time
script_info['total_stores'] = total
print('\n{} total stores : {}'.format(comp_name,script_info['total_stores']), '\n')
print('{} running time : {}'.format(comp_name,script_info['running_time']), '\n')
print('{} runBeforeInsert Done'.format(comp_name), '\n')
print('\n')
return script_info
except Exception as e:
traceback.print_exc()
script_info = {}
script_info['running_time'] = '--'
script_info['total_stores'] = 'error'
return script_info
print(e)
and import above into hangten crawler class:
def run_before_insert2(self):
rp = run_pkg_class()
rp.run_before_insert(self.get_id())
In this hangTen case, self.get_stores_2() will return a list.
"TypeError: 'list' object is not callable" occur while running.
Not sure for the reason
Python functions are first-class objects. They are like any other attribute. Just pass them directly:
import C
class A:
def x_A (self):
C.x_C(self.u_A)
class B:
def x_B (self):
C.x_C(self.u_B)
And in C, you just call it like so:
unique_function()
Given that C apparently doesn't care about the state in A and B though, I suspect these things shouldn't be classes to begin with.
If I understand correctly, you don't even need to import a module every time. Instead, you can create a basic class from which other classes will inherit the function. For example, classes B and C inherit function "power" from class A.
class A:
""" Example of class A """
def __init__(self):
self.num1 = num1
def power(self, num):
return num**3
class B (A):
""" Example of class B"""
def __init__(self, num1, num2):
super().__init__(num1)
self.num2 = num2
self.power_num1 = self.power(num1)
class C(A):
""" Example of class C"""
def __init__(self, num1, num2, num3):
super().__init__(num1)
self.num2 = num2
self.num3 = num3
def power_total(self):
print(self.power(self.num1) + self.power(self.num2)
+ self.power(self.num3))
Examples of use:
>>> c = C(1, 2, 3)
>>> c.power_total()
36
>>> b = B(2, 4)
>>> b.power_num1
8
I'm using python 3.3.4. Here is my code:
class ojaxi(object):
nomeri = 0
def __init__(self):
self.wevri = []
def damateba(self, adamiani):
if adamiani in self.wevri:
print("We Already Have That one")
else:
self.wevri.append(adamiani)
def __repr__(self):
return self.wevri
class adamiani(ojaxi):
def __init__(self, saxeli, shuasax, asaki):
self.saxeli = saxeli
self.shuasax = shuasax
self.asaki = asaki
def __str__(self):
return self
baramidze = ojaxi()
N1 = adamiani("tyler", "durden", 18)
N2 = adamiani("joe", "black", 20)
baramidze.damateba(N1)
baramidze.damateba(N2)
print(baramidze)
Problem i have is that i can't make a function print out all the members in "baramidze". I want __repr__ or __str__ to print out something like this:
["N1", "N2"]
all i get is an error saying:
__str__ returned non-string (type list)
Like the error says, you must return a string from __str__. To do what you want you may like this :
def __str__(self):
return repr(self.wevri)
You should do:
def __str__(self):
return ' '.join(self.saxeli+self.shuasax+str(self.asaki))
i have made a program but the output that i'm getting is
(<q3v3.Student instance at 0x023BB620>, 'is doing the following modules:', ' <q3v3.Module instance at 0x023BB670> <q3v3.Module instance at 0x023BB698>')
For example , the above output should give me Alice is doing following module : biology, chemistry
Help
this is my full code:
class Student :
def __init__(self,students):
self.students= students
print self.students
#def __str__(self): # when i used this i've got error type TypeError: __str__ returned non-string (type NoneType)
#print str(self.students)
class Module:
def __init__(self,modules):
self.modules = modules
print self.modules
#def __str__(self):
#print str(self.modules)
class Registrations (Student,Module):
def __init__(self):
self.list= []
self.stulist = []
self.modulist= []
def __iter__(self):
return iter(self.list)
def __str__(self):
return str(self.list)
def add(self,students,modules):
self.list.append((students,modules))
#print (self.list)
def students(self,modules):
for i in self.list:
if i[1] == modules:
self.modulist.append((i[0]))
return iter(self.modulist)
def __str__(self):
return str(self.students)
def modules(self,students):
for i in self.list:
if i[0] == students:
self.stulist.append((i[1]))
return iter(self.stulist)
def __str__(self):
return str(self.modules)
i need to import my program to be able to run it to this :
from q3v4 import *
james = Student('james')
alice = Student('alice')
mary = Student('mary')
agm = Module('agm')
ipp = Module('ipp')
r = Registrations()
r.add(james,agm)
r.add(alice,agm)
r.add(alice,ipp)
mstr = ''
for m in map(str,r.modules(alice)):
mstr = mstr+' '+m
print(alice, 'is doing the following modules:', mstr)
sstr = ''
for s in map(str,r.students(agm)):
sstr = sstr+' '+s
print(agm, 'has the following students:', sstr)
print(r)
You could define a __str__ method in your Student class, and do something like this:
def __str__(self):
return self.name # Here the string you want to print
Are you using Python 2? If so, print is a keyword, not a function. There are two ways to solve your problem:
Write print foo, bar instead of print(foo, bar).
The difference is that print(foo, bar) is actually printing out the tuple (foo, bar), which uses the repr() representation of each element, rather than its str().
At the very top of your file, write from __future__ import print_function. This will magically convert print from a keyword into a function, causing your code to work as expected.
If you are using Python 3, my answer is irrelevant.
I am trying to parametrize a function using decorator. Finally I am able to get it run as expected after lot of hit and trials. But still I am not satisfied as though it is working, it doesn't seem to be right way to do it.
Please help me improve this code.
Here is my code:
def WarmWelcome(fn):
def wrapped(DataProvider):
for name in DataProvider():
print fn(name) + ":)"
return wrapped
def DataProvider():
names=["abc","xyz","def"]
for name in names:
yield name
#WarmWelcome
def hello(name):
return "hello " +name
hello(DataProvider)
Here is the updated code:
def WarmWelcome(DataProvider):
def real_decorator(fn):
def wrapped():
for name in DataProvider():
print fn(name) + ":)"
return wrapped
return real_decorator
def DataProvider():
names=["abc","xyz","def"]
for name in names:
yield name
#WarmWelcome(DataProvider)
def hello(name):
return "hello " +name
hello()
It's also possible to provide dataset right to WarmWelcome decorator:
def WarmWelcome(*data_sets):
def _decorator(func):
def _func():
for ds in data_sets:
func(*ds)
return _func
return _decorator
#WarmWelcome(
("abc", ),
("xyz", ),
("def", ),
)
def hello(name):
return "hello " +name
Original: PHPUnit-like dataProvider implementation for Python unittest
I'm trying to make a class that is borg-like. I'd like one particular property to be shared by all the instances, but other properites I would like to be unique to the instance. Here is what I have so far:
class SharedFacility:
_facility = None
def __init__(self):
entries = {'facility': self._facility}
self.__dict__.update(entries)
def _getfacility(self):
return self._facility
def _setfacility(self, value):
self._facility = value
facility = property(_getfacility, _setfacility)
class Warning(SharedFacility):
def __init__(self, warnlevel, warntext):
SharedFacility.__init__(self)
print "Warning.__init__()"
self.warntext = warntext
self.warnlevel = warnlevel
def __call__(self):
self.facility(self.warnlevel, self.warntext)
def functionOne(a,b):
print 'functionOne: a=%s, b=%s' % (a,b)
def functionTwo(a,b):
print 'functionTwo: a=%s, b=%s' % (a,b)
####################################################
w1 = Warning(1, 'something bad happened')
w1.facility = functionOne
w2 = Warning(5, 'something else bad happened')
import pdb; pdb.set_trace()
if w1.facility is w2.facility:
print "They match!"
w1() # functionOne: a=1, b='something bad happened'
w2() # functionOne: a=5, b='something else bad happened'
w2.facility = functionTwo
if w1.facility is w2.facility:
print "They match!"
w1() # functionTwo: a=1, b='something bad happened'
w2() # functionTwo: a=5, b='something else bad happened'
The above code does not work. I'd like w1.facility and w2.facility to be a reference to the same object, but w1.warntext and w2.warntext two be two different values. I'm working with python 2.4.3 (no sense in mentioning I upgrade because I can't).
Solution:
class Warning(object):
_facility = None
def __init__(self, warnlevel, warntext):
print "Warning.__init__()"
self._warntext = warntext
self._warnlevel = warnlevel
def __call__(self):
Warning._facility(self._warnlevel, self._warntext)
def _getfacility(self):
return Warning._facility
def _setfacility(self, value):
Warning._facility = value
facility = property(_getfacility, _setfacility)
#staticmethod
def functionOne(a,b):
print 'functionOne: a=%s, b=%s' % (a,b)
#staticmethod
def functionTwo(a,b):
print 'functionTwo: a=%s, b=%s' % (a,b)
Here's what I would do:
class BorgLike:
_shared = 'default'
def __init__(self, unique):
self.unique = unique
#property
def shared(self):
return BorgLike._shared
#shared.setter
def shared(self, value):
BorgLike._shared = value
I hope you know how to use this example for your own purpose. I wasn't really sure what you wanted with your code, so I refrained from guessing and wrote a minimal example.