0
class FooBar:
     def __init__(self, value = 42):
         self.somevar = value

f = FooBar('This is a constructor argument')
f.somevar

This is a constructor argument

How can the parameter value know what kind of data it's going to be given? Int, float, string, etc? thanks.

Edited by lewashby: n/a

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by vegaseat
0

???

A guess... :)

class foobar():
    def __init__(self, foo, bar):      # constructor
        self.foo = foo
        self.bar = bar

Cheers and Happy coding

0

Generally, type checking in Python is frowned upon. If you really feel like you need to do it, though, there are a couple ways you can do this.

You could use the isinstance() function to check the type, and raise an exception if the argument of the correct type.
For instance:

class Employee:
	def __init__(self, name=None, age=None, salary=None):
		if name and (not isinstance(name, str)):
			raise TypeError('Name must be a string.')
		if age and (not isinstance(age, int)):
			raise TypeError('Age must be an integer.')
		if salary and (not isinstance(salary, float)):
			raise TypeError('Salary must be a floating point number.')
			
		self.name = name
		self.age = age
		self.salary = salary
0

Thanks but I'M not trying to find another way to do it. I just want to know how that's possible.

0

Python assigns the type by inference.
value = 42 is an integer
value = 12.34 is a flost
value = 'top' is a string
value = (1, 2, 3) is a tuple and so on ...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.