Python Forum
Creating a script with a class have specific properties
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a script with a class have specific properties
#1
I have a small txt file with fields Block, Plot, Species, and DBH. I need to create a script with a class having those properties. Within the class I need to include a method that calculates "DIB = DBH * (1/1.09)". DBH is the diameter 4.5 feet from the ground. Once I am completely done I need to run a script that imports the class and prints the results in this format:
Output:
Report 1 Block: Plot: Species: DBH: DIB: Report 2 etc.
There are a total of 9 objects. So far I am working the class but not sure I got it correct. I got no errors but I also didn't get any returns. Here is where I am. By the way I am the beginner of beginners so please don't laugh. If you do please help once you stop.

class Tree:
    def __init__(self,Block,Plot,Species,DHB):
        self.Block = Block
        self.Plot = Plot
        self.Species = Species
        self.DHB = DHB

    def assessment(self):
        if self.DHB == 4.5:
            rate = (1/1.09)
        assessment = self.DHB * rate
        return assessment
Reply
#2
It would be useful to show us small sample of the text file. And also the code where you actually read and use the class you have defined. Note that what you show right now is the class definition. You need to create an instance of the class (i.e. instantiate particular object of that class).
As to the class definition it's more or less correct. The problem that I see is the if condition in the assessment method. Unless self.DHB is equal to 4.5 you will get an error because rate will not be defined when you try to use it on line 11. Also I don't think the logic is correct all together. if I understand your requirements you want to calculate DIB property always, not only when DHB == 4.5, right?
I am going to show you something more advanced. Because DIB is calculated property, it's better it to be sort of read-only (i.e. user will not be able to alter it.

class Tree:
    def __init__(self, block, plot, species, dhb):
        self.block = block
        self.plot = plot
        self.species = species
        self.dhb = dhb
 
    @property
    def dib(self):
        return self.dhb/1.09
        
    def report(self, report):
        return 'Report {}\nBlock: {}\nPlot: {}\nSpecies: {}\nDBH: {:0.3f}\nDIB: {:0.3f}'.format(report, self.block, self.plot, self.species, self.dhb, self.dib)
  
#example how to instanciate object of class Tree
#ignore numbers if they don't make business sense
  
tree = Tree(block=1, plot=5, species=7, dhb=200)
print(tree.report(1))
Output:
Report 1 Block: 1 Plot: 5 Species: 7 DBH: 200.000 DIB: 183.486 >>>
I changed variable names to be compliant with PEP8 style guide. also Tree.report() method is just an example. you can take it from here and play a bit with it
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you. I will have to look at it with fress eyes tomorrow. I may have asked wrong. The end script imports the class to generate the report results. I started with trying to create the class. I have not worked the script to import it yet. Well, I did a few lines but really wasn't sure where to go with it.
Reply
#4
Probably I misunderstood the following statement, i.e. you need to use the class in order to get any result (if no errors, etc.):
(Oct-11-2018, 04:27 AM)dvldgs05 Wrote: I also didn't get any returns

Something I didn't mention is that when you read data from the text file they will come as str and you need to convert to some numeric type in order to make calculations.

Finally, unless this is assignment (e.g. at university) and you are required to use custom class, there are more readily available solutions that you cam use to the same effect (e.g. namedtuple) in order to generate the report.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Here is a sample of the txt file. When I ran the script I get the same as my original script which is no return but no error indicated.
Block Plot Species DBH
17 A Cedar 32.5
17 A Fir 35.7
17 B Spruce 45.6
Reply
#6
Thank you for you help. I need to create a script that passes the values for each line of text (like the sample in my previous reply) to create a tree object, and then prints the properties of the object as opposed to keeping the print function in the class. I want to be able to use it differently and repeatedly. At this point I am brain dead so would welcome any suggestions and/or references to use. Preferably something on the Python for Dummies level that I can access via the web. I believe it should be something like this but I feel there is a need for a for loop unless I am trying to make this harder than it needs to be.

import tree2class
mytree2 = tree2class.tree2("DHB", "")
print "Report: ", mytree2.Block, mytree2.Plot, mytree2.Species, mytree2.DHB
myDIB = self.dhb/1.09
print myDIB
Reply
#7
Now I will move this to homework section as it's obviously an assignment.
Then, I will ask again to use proper tags when post code, traceback, output, etc. I have added tags for you in your first post. See BBcode help for more info.
Finally, check our tutorials on working with files and also on classes. You need to understanding the basic concepts of OOP. To understand my use of @property decorator check this tutorial
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
Is this what you want?

class Tree:
	def __init__(self,Block,Plot,Species,DHB):
		self.Block = Block
		self.Plot = Plot
		self.Species = Species
		self.DHB = DHB

	def assessment(self):
		if self.DHB == 4.5:
			rate = (1/1.09)
			assessment = self.DHB * rate
			return assessment

	def __str__(self):
		return "Block: " + str(self.Block) + "\n" + "Plot: " + self.Plot + "\n" + "Species: " + self.Species + "\n" 	+ "DHB: " + str(self.DHB) + "\n"		

class tree_inputter():

	def __init__(self):
		self.trees = []
		
	def get_data(self):
		with open("the_data", "r") as a_file:
			for a_line in a_file:
				temp = a_line.split(" ")
				
				Block = int(temp[0])
				Plot = temp[1]
				Species = temp[2]
				DHB = temp[3]
				
				self.trees.append(Tree(Block, Plot, Species, DHB))
		
	def show(self):
	
		for tree in self.trees:
			print tree
			
			
if __name__=="__main__":
	ti = tree_inputter()
	ti.get_data()
	ti.show()
	
Reply
#9
Thanks marienbad. I think this scripting is not for me super discouraged. I need to use the class within a main script where the main script does the printing. So for each line of text, it passes the values to create a tree object, and then prints the properties of the object. For me this is like being able to somewhat understand a foreign language being spoken but not knowing enough yet to say anything recognizable. I feel like the main script should go something like this(however it did not work):

import tree2class
mytree2 = tree2class.tree2("DHB", "")
print "Report: ", mytree2.Block, mytree2.Plot, mytree2.Species, mytree2.DHB
myDIB = self.dhb/1.09
print myDIB
Reply
#10
May I ask why the 'tree' in 'print(tree.report(1))' isn't capitalized? I am confused about this point. Because in previous sentences nothing is defined as 'tree', but only the class 'Tree'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I need help writing this code for string properties and methods hannah71605 4 3,109 Mar-22-2021, 12:36 PM
Last Post: menator01
  Creating Email Message Class in Python QuavoJ 1 2,147 Jul-20-2020, 08:30 PM
Last Post: Yoriz
  Sort objects by protected properties. Sigriddenfeta 1 1,886 Mar-17-2020, 04:11 AM
Last Post: Larz60+
  Creating class with getters and setters. amandacstr 3 2,339 Jun-19-2019, 07:10 PM
Last Post: nilamo
  newbie questions about objects properties... slowbullet 2 2,632 Aug-12-2018, 01:12 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020