Im writing a basic program in Python.
In the program, there is an array called abc. The array contains the following data:
birthdate and name.
Instead of using:
abc[1]
I want to create sub function, like:
abc.name()
That will return the value of abc[1]
How can i create a function like this (with dot)? Thanks!!
You will want to use a class like this:
class abc():
def __init__(self, birthday, name):
self.__birthday = birthday
self.__name = name
def birthday(self):
return self.__birthday
def name(self):
return self.__name
Now just create abc
person = abc('5/04/1984', 'Nick Stone')
And get the data like so:
bday = person.birthday()
name = person.name()
As said, you can't add such 'function' to your value, it's necessary to create a class definition if you need to use .dot notation. Basic example:
class abc():
# constructor, initializing object state
def __init__(self,item):
self.item=item
# here you define name and body of your function
def name(self):
# return just second item from our "item" value (string, array, list, etc.)
return self.item[1]
Now, you can create object of class abc and call it's 'name function':
> myData=abc('123')
> myData.name()
'2'
> myData=abc(['birth','name'])
> myData.name()
'name'
Related
I have just started learning OOP in python and I have learned basics like creating class and it's methods, variables and Constructors. Now to create an object we use following steps.
class Example: #Class
name = None
number = None
def __init__(self, name, number): #Constructor
self.name = name
self.number = number
#Step 1
harry = Example("Harry", 45) #Creates an Object
Now here we have manually created Object of Example class named harry.
I have a question that how to create an object with a function.
Like we created a function outside the class and we passed arguments to like name and number and when that function is called it will create a Object of class.
Are you looking for something like this ?
def build_object(name, number):
# returns Example object initialized with name and number
return Example(name, number)
You're talking about Factory Methods
To create objects in functions and returning it would be like:
class Example:
def __init__(self, name, number):
self.name = name
self.number = number
def object_creator(name, number):
new_obj = Example(name, number)
return new_obj
if __name__ == "__main__":
example_object = object_creator("Iago", 1)
print(example_object.name)
print(example_object.number)
Not sure what do you mean exactly.
in oop you can create a function/method then you can from it's object or class.
class Example: #Class
name = None
number = None
def __init__(self, name, number): #Constructor
self.name = name
self.number = number
def your_function(self, x, y):
return x + y
#Step 1
harry = Example("Harry", 45) #Creates an Object
result = harry.your_function(5, 2)
print (result)
output : 7
I'm new to python and as I was doing an assignment for class, I got stuck using init method.
class Customer(object):
def __init__(self, number, name):
self.name = name
self.number = number
self.orders = []
def addorder(self, order):
self.orders.extend(order)
return self.orders
def __str__(self):
return str(self.orders)
Customer('308','John').addorder((1,2,3,4))
print(Customer('308','John'))
The output is an empty list [].
I want the output to be [1,2,3,4]
What am I doing wrong here?
The issue is that you have two Customer objects. I.e. your print line:
print(Customer('308','John'))
Is creating a new Customer object with a number of '308' and a name of 'John'. It's completely unrelated to the customer on the previous line.
To fix this, you should assign your first object to a variable (think of it like a handle, that lets you access the object), and then print that:
john = Customer('308','John')
john.addorder((1,2,3,4))
print(john)
You're creating two instances of the class
class Customer(object):
def __init__(self, number, name):
self.name = name
self.number = number
self.orders = []
def addorder(self, order):
self.orders.extend(order)
return self.orders
def __str__(self):
return str(self.orders)
customer = Customer('308','John')
customer.addorder((1,2,3,4))
print(customer)
Keep in mind that each time you "call" a class, you instantiate a new object (this is why in many languages other than Python, this actually requires the keyword new). So, in your example, you're instantiating two different objects (that don't share their properties). Instead, you should save them in a variable:
customer = Customer("308", "John")
customer.addorder((1, 2, 3, 4))
print(customer)
I am trying to find a way for getting all attributes to evaluate after one attribute change within the class, without calling a function outside the class.
class Students:
def __init__(self, name, mylist):
self.name = name
self.subjects = mylist
self.credits = len(self.subjects) * 2
def credits_calc(self):
self.credits = len(self.subjects) * 2
return self.credits
john = Students("John", ["Maths", "English"])
print(john.subjects)
print(john.credits)
john.subjects.append("History")
print(john.subjects) # --> subjects attribute updated.
print(john.credits) # --> obviously not updated. Still returns initial value.
I have to call the function outside the class to to have the other attributes updated
john.credits_calc() # I know I can take the returned value.
print(john.credits) # --> updated after calling the function.
So my question is how to get the other attributes to evaluate if one attribute is changed without the need to manually call the function later.
What you are looking for is the property decorator. There are additional methods you can add on to this, particularly the fset and fdel logic of this attribute, the code below simply defines the fget behavior.
class Students:
def __init__(self, name, mylist):
self.name = name
self.subjects = mylist
#property
def credits(self):
return len(self.subjects) * 2
john = Students("John", ["Maths", "English"])
print(john.credits) # 4
john.subjects.append("History")
print(john.credits) # 6
There is two classes - Company and Project. Company object has property projects as list, that should indicate list of Project instances that is added to the company
Here is realization of classes and methods to add projects to the company:
class Company(object):
def __init__(self, companyname):
self.companyname = companyname
self.projects = list()
def show_projects(self):
print(f"Company projects: {self.projects}")
def add_project(self, name):
return self.projects.append(Project(name))
class Project(object):
def __init__(self, name):
self.name = name
But when I try to initialize company, then project and add it to company, add add_project returns not project.name, but object itself, so i.e. output of this:
firm = Company("New")
first = Project("first")
print(first.name)
firm.add_project(first.name)
firm.show_projects()
will be:
first
Company projects: [<__main__.Project object at 0x00A54170>]
Why is it passing not name, but object itself? Can't find out what is missing here.
firm.projects is a list so in show_projects when you print it it will be a list of objects. One solution would be to modify show_projects to format the list into a comma separated string first:
def show_projects(self):
formatted_projects = ','.join([p.name for p in self.projects])
print(f"Company projects: {formatted_projects}")
I have these Objects:
class Object(object):
def __init__(self, name, *parameters):
self.name = name
self.parameters = parameters
def name(self):
return self.name
def parameters(self):
return self.parameters
class Parameter(object):
def __init__(self, name, value):
self.name = name
self.value = value
My aim is to get all parameters of 1 object in a dictionary, but it needs to end up like this:
{ParameterOne: "ValueOne", ParameterTwo: "ValueTwo"}
Since I have to be able to give the parameters different names, I can't do it like this:
class Parameter(object):
def __init__(self, value):
self.ParameterOne = value
I tried it like this which obviously didn't work:
data = {}
for parameter in object.parameters:
data.update(vars(parameter))
Is there any way to achieve this?
data = {parameter: ''.join(['Value ', str(index)])
for index, parameter in enumerate(object.parameters)}
This will give you {parameter0: 'Value 0', ...} If you want to get the English words for the numbers, you;ll have to either roll your own function for it or use an external package like inflect.
Just an observation, but most dictionaries would have the string mapping to the object, not the other way around. Is there some reason you're doing it this way?
EDIT:
Rereading your question, are you looking for
data = {parameter: parameter.name for parameter in object.parameters}
I think you might want to try instead
data = {parameter.name: parameter.value for parameter in object.parameters}